Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 8.4 — useImperativeHandle: Exposing a Small API
React · Example 3 of 3

When not to use it: open and close with a prop

Opening is just data: isOpen. Anyone reading App sees when the panel shows, DevTools shows the state, and the panel can't get out of sync with the parent. An open() method on a handle would hide all that.

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.

01

Write a VideoBox component that exposes only play() and pause() to its parent, using an internal ref on a <video> element.

02

Write an uncontrolled NoteForm (inputs with defaultValue) that exposes reset(), which empties every field and focuses the first one.

Explain it without notes

01

What does useImperativeHandle do and why would you use it instead of forwarding a ref to a DOM node?

02

Explain each argument of useImperativeHandle(ref, createHandle, deps).

03

When should you not use useImperativeHandle? Give an example and the better alternative.

When not to use it: open and close with a prop

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

HelpPanel rendered, isOpen = false
HelpPanel rendered, isOpen = true