Skip to content

Imperative Handles

The Course
•
20 min study

Most of the time, a parent changes a child by changing its props. A few actions don't fit that model, because they're commands rather than states: "focus", "scroll to the top", "play from the start". For those, a component can give its parent a handle: a small object of methods, reached through a ref.

Timers with a handle React · 4 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useRef } from "react"; import Timer from "./Timer.jsx"; export default function App() { const focusRef = useRef(null); const breakRef = useRef(null); return ( <main> <h1>Session timers</h1> <Timer ref={focusRef} label="Focus" /> <Timer ref={breakRef} label="Break" /> <div className="toolbar"> <button onClick={() => focusRef.current.start()}>Start focus</button> <button onClick={() => { focusRef.current.pause(); breakRef.current.start(); }}>Take a break</button> <button onClick={() => { focusRef.current.reset(); breakRef.current.reset(); }}>Reset both</button> </div> </main> ); } import { useEffect, useImperativeHandle, useState } from "react"; // A timer that a parent can start, pause and reset through its ref. export default function Timer({ ref, label }) { const [seconds, setSeconds] = useState(0); const [running, setRunning] = useState(false); useEffect(() => { if (!running) return; const id = setInterval(() => setSeconds((s) => s + 1), 1000); return () => clearInterval(id); }, [running]); useImperativeHandle(ref, () => ({ start: () => setRunning(true), pause: () => setRunning(false), reset: () => { setRunning(false); setSeconds(0); }, }), []); return ( <p className="card"> {label}: <strong>{seconds} s</strong> {running ? "(running)" : ""} </p> ); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Press Start focus, then Take a break, then Reset both.

useImperativeHandle

JavaScript
useImperativeHandle(ref, () => ({
  start: () => setRunning(true),
  pause: () => setRunning(false),
  reset: () => {
    setRunning(false);
    setSeconds(0);
  },
}), []);

ref arrives as a prop, as in the intermediate course, but instead of a DOM element the parent gets the object this function returns. focusRef.current is { start, pause, reset }, nothing more. The timer's state and its interval stay private.

That's the point: a handle is a narrow public API. The parent can't reach into the timer and set seconds to 500, only ask it to start, pause or reset.

When not to

running could have been a prop: <Timer running={focusRunning} />, with the parent holding the state. That's usually better. It's declarative, the parent can show "running" elsewhere, and the timer can't drift out of sync with what the parent thinks.

Reach for a handle only when:

  • the action is a one-off command, such as focus, scroll or play;
  • or the child must own the state, and the parent only needs to nudge it.

Predict

Delete the pause line from the handle, and press Take a break. What happens?

Check your prediction

The console reports focusRef.current.pause is not a function, and the break timer doesn't start, because the error stops the handler before it gets there. The handle is the whole API: if a method isn't in it, the parent can't call it.

Exercise

Remember the longest session

Add a getLongest() method to the handle that returns the longest number of seconds the timer has reached before a reset. Add a Longest focus button to App that logs longest focus: 7.

Your working space React · 4 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useRef } from "react"; import Timer from "./Timer.jsx"; export default function App() { const focusRef = useRef(null); const breakRef = useRef(null); return ( <main> <h1>Session timers</h1> <Timer ref={focusRef} label="Focus" /> <Timer ref={breakRef} label="Break" /> <div className="toolbar"> <button onClick={() => focusRef.current.start()}>Start focus</button> <button onClick={() => { focusRef.current.pause(); breakRef.current.start(); }}>Take a break</button> <button onClick={() => { focusRef.current.reset(); breakRef.current.reset(); }}>Reset both</button> </div> </main> ); } import { useEffect, useImperativeHandle, useState } from "react"; // A timer that a parent can start, pause and reset through its ref. export default function Timer({ ref, label }) { const [seconds, setSeconds] = useState(0); const [running, setRunning] = useState(false); useEffect(() => { if (!running) return; const id = setInterval(() => setSeconds((s) => s + 1), 1000); return () => clearInterval(id); }, [running]); useImperativeHandle(ref, () => ({ start: () => setRunning(true), pause: () => setRunning(false), reset: () => { setRunning(false); setSeconds(0); }, }), []); return ( <p className="card"> {label}: <strong>{seconds} s</strong> {running ? "(running)" : ""} </p> ); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

The longest value isn't shown, so a ref inside Timer is enough. Update it in reset, before setting the seconds back to 0, and compare with the current seconds in getLongest.

Hint 2: a first step

getLongest reads seconds, which changes. Either put seconds in the handle's dependency list, or keep the latest seconds in a ref too.

Show one solution
JavaScript
const longestRef = useRef(0);

useImperativeHandle(ref, () => ({
  start: () => setRunning(true),
  pause: () => setRunning(false),
  reset: () => {
    longestRef.current = Math.max(longestRef.current, seconds);
    setRunning(false);
    setSeconds(0);
  },
  getLongest: () => Math.max(longestRef.current, seconds),
}), [seconds]);
JSX
<button onClick={() => console.log("longest focus:", focusRef.current.getLongest())}>Longest focus</button>

Was this article helpful?

Your response is saved on this device.