Command Palette

Search for a command to run...

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

Expose focus and clear, hide the DOM node

The parent's ref holds { focus, clear }, not the input. It can clear and focus the box, but it can't touch styles or remove the node. (The second small root at the bottom exists only to peek at the handle.)

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.

Expose focus and clear, hide the DOM node

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

value now: "" | focused: true
handle keys: [ 'focus', 'clear' ] | style: undefined