React · Frontend system thinking
How do refs and useImperativeHandle expose imperative component APIs?
Short answer
A ref lets a parent call methods on a child. useImperativeHandle limits what the parent can access, exposing only the actions you choose, such as focus or scroll.
React is mostly declarative, but some components need an imperative API: focusing an input, scrolling a list, playing a video or opening a dialog. Refs provide the connection. useImperativeHandle customises the value a parent receives instead of exposing the entire DOM node.
const FancyInput = forwardRef(function FancyInput(props, ref) {
const inputRef = useRef(null);
useImperativeHandle(ref, () => ({
focus() {
inputRef.current?.focus();
},
selectAll() {
inputRef.current?.select();
},
}), []);
return <input ref={inputRef} {...props} />;
});React 19 refs
- Function components can receive
refas a normal prop in React 19 forwardRefremains for compatibility with older React versionsuseImperativeHandlestill works with either approach- Callback refs can run cleanup logic when a node is detached
Keep the exposed surface small. A handle with five methods is usually a sign that the component should expose state or children instead. Prefer props and callbacks for normal data flow; use an imperative handle only for actions that genuinely belong to the DOM or a third-party instance.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1How does React 19 change ref forwarding?
- 2When is useImperativeHandle better than exposing a DOM ref?
- 3What happens to a ref when its element unmounts?
- 4How do callback refs support cleanup?
Say it in the interview
Refs let a parent invoke behaviour on a child, and useImperativeHandle controls exactly what that ref exposes. I use it for focus, scroll, playback or dialog controls instead of leaking the whole DOM node. In React 19 a function component can accept ref as a prop, while forwardRef is still there for older code. I keep the API narrow and avoid using it to replace ordinary state flow.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live React mock interview and get scored feedback on depth, clarity and confidence.