Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 8.1 — Refs: Remembering Without Re-rendering
React · Example 1 of 3

State updates the screen, a ref doesn't

Three ref clicks: the value really goes up to 3, but nothing renders and the screen still says 0. One state click renders, and only then does the screen catch up with the ref.

useRef gives a component a box, { current: value }, that keeps its value between renders but doesn't cause a re-render when you change it; use it for values the screen doesn't show, such as timer ids and previous values.

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 SearchBox that logs searching for: <text> only when the user stops typing for 300 ms (a debounce). Keep the timeout id in a ref.

02

Write a button that ignores clicks while a fake save (setTimeout of 500 ms) is running, using a ref as an isSaving flag, and logs saved when done.

Explain it without notes

01

What is the difference between a ref and state?

02

Why is a timer id a good fit for a ref, and what goes wrong with a normal variable?

03

Why shouldn't you read or write ref.current during rendering? Is there an exception?

04

How does a component remember the previous value of a prop?

State updates the screen, a ref doesn't

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

render, stateCount = 0
refCount.current is now 1
refCount.current is now 2
refCount.current is now 3
screen: Ref on screen: 0
render, stateCount = 1
screen: Ref on screen: 3