React · Frontend system thinking

How do refs and useImperativeHandle expose imperative component APIs?

MediumrefsuseImperativeHandleimperative APIUpdated Oct 2026
Quiz this track

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.

jsx
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} />;
});
The parent can focus or select, but cannot reach the raw input node or change arbitrary DOM properties.

React 19 refs

  • Function components can receive ref as a normal prop in React 19
  • forwardRef remains for compatibility with older React versions
  • useImperativeHandle still 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.

Do not use an imperative handle to bypass state ownership. If the parent needs to know whether the child is open or selected, that is state to lift or share, not a method to query.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1How does React 19 change ref forwarding?
  2. 2When is useImperativeHandle better than exposing a DOM ref?
  3. 3What happens to a ref when its element unmounts?
  4. 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.