Remembering the previous value in an effect
Nothing logs on the first render, because old and new are equal. After that, each change logs the old and the new price. The ref is read and written only inside the effect.
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.Expected console output
price went up: 100 -> 110
price went up: 110 -> 120
price went down: 120 -> 115