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.
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.
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
What is the difference between a ref and state?
Why is a timer id a good fit for a ref, and what goes wrong with a normal variable?
Why shouldn't you read or write ref.current during rendering? Is there an exception?
How does a component remember the previous value of a prop?
Preview
Console
Nothing logged yet.