MediumHooks📖 Theory Question

What are useImperativeHandle and forwardRef?

💡

Hint

forwardRef passes ref through to a child; useImperativeHandle customizes what the parent sees on that ref

Full Answer

forwardRef — lets a parent component pass a ref to a DOM node or component instance inside a child.

useImperativeHandle — customizes what a parent receives via that ref, exposing only a controlled API instead of the raw DOM node.

// Without forwardRef — parent can't reach inner input
function Input(props) {
  return ;
}

// ✅ With forwardRef — parent can call .focus(), etc.
const Input = forwardRef(function Input(props, ref) {
  return ;
});

// Parent
function Form() {
  const inputRef = useRef(null);
  return (
    <>
      
      
    
  );
}

// ─── useImperativeHandle — expose limited API ──────────────────────────────
const FancyInput = forwardRef(function FancyInput(props, ref) {
  const inputRef = useRef();

  useImperativeHandle(ref, () => ({
    focus: () => inputRef.current.focus(),
    clear: () => { inputRef.current.value = ''; },
    // Parent can NOT access inputRef.current directly — only these two methods
  }));

  return ;
});

const ref = useRef();
ref.current.focus(); // ✅
ref.current.value;   // ❌ undefined — not exposed
💡 Use forwardRef sparingly — it tightly couples parent to child internals. Most of the time you can solve the problem with a controlled component pattern instead. Use it mainly for UI library components (inputs, modals).

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint