Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 8.2 — Reaching the DOM with Refs
React · Example 2 of 4

When React sets and clears a ref

First render: null, because the node doesn't exist yet; both effects see the node. When the box is hidden, the render still sees the old node (rendering happens before the commit), and the effects see null because React cleared the ref during the commit.

Put a ref on a JSX element with the ref attribute and React stores the real DOM node in ref.current after the commit, so you can focus it, scroll it into view or measure it; for a whole list of elements, use a callback ref that fills a Map.

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

Build a chat box: a list in a scrolling container and an input. After each new message is added, scroll the container to the bottom.

02

Make a CopyField with a read-only input and a Copy button that selects all the text in the input.

Explain it without notes

01

How do you get a DOM node in React, and when is it available?

02

When does React set a ref to null?

03

How do you keep refs to a list of elements whose length changes?

04

What can you safely do with a DOM ref, and what shouldn't you do?

When React sets and clears a ref

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

render:         null
layout effect:  <div.box>
effect:         <div.box>
--- hide the box ---
render:         <div.box>
layout effect:  null
effect:         null