useImperativeHandle: Exposing a Custom API from a Child Component

Hands-on practice for this lecture. Work through the exercises and quizzes to reinforce what you've learned.

1

Exercise 1 of 1

useImperativeHandle Quiz

Three questions on forwardRef and useImperativeHandle — what the parent sees, what it cannot access, and when not to use it.

1
const FancyInput = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    focus: () => inputRef.current.focus(),
    clear: () => { inputRef.current.value = ''; },
  }));
  const inputRef = useRef(null);
  return <input ref={inputRef} {...props} />;
});

What does the parent get when it accesses ref.current?

2
// Parent component
const ref = useRef(null);
// After mount:
ref.current.scrollIntoView(); // ← will this work?

Given the FancyInput above, does this work?

3
// Should you use useImperativeHandle for this?
function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(c => c+1)}>{count}</button>;
}

Would you add forwardRef + useImperativeHandle to Counter?

0/3 answered

💡 Use useImperativeHandle when you need to expose a custom imperative API from a component — typically for DOM operations like focus, scroll, or animations. Never use it to replace what props and state can express cleanly.

Practice: useImperativeHandle: Exposing a Custom API from a Child Component — Interactive Exercises | Durgesh Rai