QuestionsReact

forwardRef and useImperativeHandle

Refs & Imperative HandlesMediumReact

How do you let a parent call a method on a child component (e.g. focus an input inside a custom <TextField>), and when is that appropriate?

What it tests

Knowing the escape hatch from declarative data flow — and its guardrails.

Approach & answer

Refs don't pass through components by default — a ref on <TextField> would point at the component instance, not its inner <input>. forwardRef lets a component receive a ref and forward it onward. But you usually don't want to expose the raw DOM node; you want a narrow imperative API. useImperativeHandle customises what the ref exposes — you return an object with just the methods the parent should call (focus, scrollIntoView, clear), hiding everything else. This is the sanctioned escape hatch from React's declarative model, for the handful of things that are genuinely imperative: focus, text selection, media playback, scroll, triggering animations. The guardrail: reach for it only when the same result can't be expressed as props/state flowing down. If a parent wants to 'tell' a child something declaratively, that's a prop, not an imperative call. Note that in React 19, ref is passed as a regular prop to function components, so forwardRef is on its way out — but useImperativeHandle stays for shaping the exposed API. Overusing imperative handles recreates the tangled parent-reaches-into-child coupling that declarative React was designed to avoid.

Use this technique when

Parent must imperatively trigger focus/scroll/play on a child → forwardRef + useImperativeHandle exposing a narrow API.

References

jsx