Sub topic 6
Keeping timer IDs and other non-visual values
This chapter assumes you know useState, basic useEffect, JavaScript closures, and the idea that a ref is a container whose .current value survives renders. Here you will use refs to hold values that the screen never shows.
Why some values do not belong in state
Some values matter to your logic but never appear in the UI. Examples are a timer ID, a WebSocket object, a previous scroll position, or a flag that says "a request is in flight."
If you put such a value in state, every change schedules a re-render that produces the same output. A ref avoids that. Writing to ref.current does not trigger a render, and the value stays the same between renders.
A quick test: if changing the value should change what the user sees, use state. If not, a ref is usually the better fit.
Example: a stopwatch
The displayed seconds are state, because they appear on screen. The interval ID is a ref, because only the Start and Stop handlers need it.
import { useEffect, useRef, useState } from 'react';
export function Stopwatch() {
const [seconds, setSeconds] = useState(0);
const intervalRef = useRef(null);
function start() {
if (intervalRef.current !== null) return;
intervalRef.current = setInterval(() => {
setSeconds((s) => s + 1);
}, 1000);
}
function stop() {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
useEffect(() => {
return () => clearInterval(intervalRef.current);
}, []);
return (
<div>
<p>{seconds}s</p>
<button onClick={start}>Start</button>
<button onClick={stop}>Stop</button>
</div>
);
}Walk through the three parts:
startchecksintervalRef.current. If an interval already exists, it returns. This stops a double click from creating two timers.stopclears the interval and resets the ref tonull. That reset is what letsstartwork again.- The effect has an empty dependency array, so its cleanup runs only when the component unmounts. It clears any running interval so the timer does not keep calling
setSecondson a component that is gone.
The setSeconds((s) => s + 1) form reads the latest state, so the interval callback does not go stale even though it was created during an earlier render.
What happens when you use a local variable instead
A plain let variable inside the component does not work. Each render runs the function again and creates a new variable, so a later click handler would not see the ID from an earlier render.
The ref avoids this because React returns the same object on every render.
Common errors
- Forgetting cleanup. If the component unmounts while the interval runs, the timer keeps going. Always clear it in an effect cleanup.
- Not resetting the ref. After
clearInterval, set the ref tonull. Otherwise a guard such as!== nullblocks the next start. - Showing a ref value in JSX. If you render
{intervalRef.current}, the screen will not update when it changes. Move that value to state. - Reading or writing refs during render. Do this in event handlers and effects instead. The next chapter covers why.
Exercise
In the stopwatch, why is seconds stored in state while intervalRef is stored in a ref?
Show answer
seconds is displayed, so changing it must trigger a re-render. The interval ID is never shown, so storing it in a ref lets you change it without an unneeded re-render while it still persists between renders.