Sometimes a component needs to remember something that isn't shown: a
timer's id, the previous value of a prop, how many times something happened.
State would work, but changing state re-renders the component, which is wasted
work when nothing on screen changes. For these, React has refs:
JavaScript
const intervalRef = useRef(null);
useRef returns a plain object, { current: null }. It's the same object
on every render. Read and change intervalRef.current in event handlers or
effects, rather than during render.
Changing it does not re-render the component.
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Press Start, wait, then Stop. start stores the interval's id in
intervalRef.current, and stop reads it back to clear it. The id never
appears on screen, so it doesn't need to be state. Being a ref also means it
survives every re-render the ticking causes:
JavaScript
function start() { setRunning(true); intervalRef.current = setInterval(() => { setElapsed((e) => e + 1); }, 1000);}function stop() { setRunning(false); clearInterval(intervalRef.current);}
Predict: a ref on screen
While the timer is stopped, press Lap three times. Watch the console
and the Laps line. Then press Start.
Check your prediction
The console counts up, laps is now 1, 2, 3, but the page still says
Laps: 0. Changing a ref doesn't re-render, so the screen shows whatever
lapsRef.current was during the last render. Press Start, and the first
tick re-renders the component: Laps: 3 appears suddenly:
JavaScript
function lap() { lapsRef.current = lapsRef.current + 1; console.log("laps is now", lapsRef.current);}
That's the rule in action: if it's shown on screen, it's state. Refs are
for values the screen doesn't depend on. Reading or writing ref.current
during render, as the Laps line does, is a bug waiting to happen. Read and
write refs in event handlers and effects.
State or ref?
State
Ref
Changing it re-renders
Yes
No
Value during a render
A snapshot, fixed for that render
Whatever it is right now
Use for
Anything shown on screen
Timer ids, DOM elements, values the screen doesn't show
Your turn
Exercise
Fix the laps
Make Laps update straight away when you press Lap, stopped or running.