An interactive demo of useImperativeHandle: a child exposes a small, curated set of methods through a ref, so a parent can command it imperatively — without lifting everything into props.
▶ Live: https://useimperativehandle.pages.dev/
React is declarative — you describe state, React updates the DOM. But some actions are inherently imperative: focus a field, play a video, scroll somewhere, run an animation. For those, a child can hand its parent a small remote control:
// child (React 19: ref is a normal prop)
function FancyInput({ ref }) {
const el = useRef(null);
useImperativeHandle(ref, () => ({
focus: () => el.current.focus(),
clear: () => { el.current.value = ""; },
shake: () => { /* animate */ },
}), []);
return <input ref={el} />;
}
// parent
const inputRef = useRef(null);
<FancyInput ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>focus</button>The demo drives two children entirely through refs: an input (focus / clear / shake) and a fake player (play / pause / reset), with a log of every method call.
You could do <input ref={ref} /> and hand the parent the raw element — but then the parent can do anything: read .value, mutate styles, remove it. There's no contract, and it breaks when the child's internals change. useImperativeHandle lets the child expose exactly the verbs it wants (three methods, nothing else) — capabilities, not internals.
In React 19, ref is a normal prop, so forwardRef is no longer required — just accept ref and pass it to useImperativeHandle. In React ≤ 18, wrap the child in forwardRef((props, ref) => …); the hook is otherwise identical.
Use it for genuinely imperative actions that don't map to props: focus()/select(), media play()/pause()/seek(), scrollIntoView(), triggering an animation, opening/closing a <dialog>, resetting a complex widget.
Don't use it to share data or state — that's what props, lifting state up, and context are for. It's an escape hatch; if you're calling child methods to keep things in sync, you probably want declarative state flow instead.
React 19 · TypeScript · Vite.
npm install
npm run devMIT © 2026 dev48v — dev48v.infy.uk