React Reference ยท Effect and Ref Hooks
React useImperativeHandle hook
Reference for React useImperativeHandle: expose a small set of methods like focus() or reset() to a parent through a ref instead of the whole DOM node.
When a parent puts a ref on your component, it normally wants a DOM node. Handing over the raw node lets the parent do anything to it. useImperativeHandle lets you replace that with your own object, such as { focus, clear }, so the parent can call only the methods you choose.
You call it inside the child with the ref the child received, a function that builds the handle, and an optional dependency array. It is an escape hatch: if the parent can do the job with props, prefer props.
useImperativeHandle(ref, () => ({ focus() { /* ... */ } }), []);
Try it
The parent sees only focus, clear. It cannot read value or change styles through the ref, because it never got the node.
Syntax
useImperativeHandle(ref, createHandle, dependencies?) // createHandle: () => handle
| Name | Description |
|---|---|
ref |
The ref passed to the component: a prop in React 19, or the second argument of forwardRef before. |
createHandle |
A function with no arguments that returns the object to expose. |
dependencies |
Optional array of reactive values createHandle uses. The handle is rebuilt when one changes. Without the array it is rebuilt on every render. |
Returns: nothing (undefined).
Edge cases: the handle is attached after the commit and detached (set to null) on unmount. A parent using the ref during its own render sees null.
Usage notes
- Expose actions, not state. Methods like
focus(),scrollTo(),reset()are good handles. If the parent needs a value, pass it with props or lift state up. - List dependencies. If
createHandlereads props or state, include them, or the handle calls stale values. The lint rule checks this. - Do not overuse. A handle makes data flow harder to follow than props. Before adding one, check whether a prop such as
autoFocusor a changingkeydoes the job. - Function components only. In class components, the instance itself is the ref value.
- React 19 lets you read
refdirectly from props;forwardRefis still supported but no longer needed. - Calls run in handlers and effects, never during render.