A chat log the parent can scroll and reset
Scrolling is a DOM action with no prop, so a small handle is a good fit. The messages themselves still arrive as a prop.
useImperativeHandle(ref, () => ({ ...methods }), deps) makes a parent's ref point at an object you choose instead of a DOM node, so you expose a few safe methods such as focus, scrollToBottom or reset and keep the rest of your component private.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a VideoBox component that exposes only play() and pause() to its parent, using an internal ref on a <video> element.
Write an uncontrolled NoteForm (inputs with defaultValue) that exposes reset(), which empties every field and focuses the first one.
Explain it without notes
What does useImperativeHandle do and why would you use it instead of forwarding a ref to a DOM node?
Explain each argument of useImperativeHandle(ref, createHandle, deps).
When should you not use useImperativeHandle? Give an example and the better alternative.
Preview
Console
Nothing logged yet.Expected console output
at the bottom: true
at the top: true