When declarative is not enough
React prefers describing UI as a function of state, but some actions are inherently imperative: focusing an input, scrolling to a node, playing a video, or measuring size. Refs are the escape hatch.
- A ref is a mutable container with a current property.
- Attach it to an element to receive the underlying DOM node after mount.
- Refs also hold any mutable value that should persist across renders without triggering a re render.
Exposing a custom API
By default a parent can only get the DOM node of a child. To expose custom methods, the child uses useImperativeHandle to define exactly what the parent ref can call, such as a focus or reset method.
This keeps the imperative surface small and intentional rather than leaking the whole internal DOM.
- Forward the ref into the child.
- In useImperativeHandle, return an object of allowed methods.
- The parent calls them through ref current.
Use refs for the rare imperative moments, keeping the rest of the app declarative.
Key idea
Refs reach DOM nodes or persist mutable values, and useImperativeHandle exposes a small, deliberate imperative API to parents.