Hands-on practice for this lecture. Work through the exercises and quizzes to reinforce what you've learned.
Exercise 1 of 1
Three questions on forwardRef and useImperativeHandle — what the parent sees, what it cannot access, and when not to use it.
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?
// Parent component const ref = useRef(null); // After mount: ref.current.scrollIntoView(); // ← will this work?
Given the FancyInput above, does this work?
// 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.