Command Palette

Search for a command to run...

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

A stopwatch keeps its interval id in a ref

The time is shown, so it is state. The interval id is never shown, so it lives in a ref, where the Stop handler of a later render can still find it.

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?

A stopwatch keeps its interval id in a ref

Preview

Press Run to see the page.

Console

Nothing logged yet.