Sub topic 6
Keeping timer IDs and other non-visual values
This chapter covers one of the most common jobs for useRef: holding values your component needs to remember but never shows on screen. It assumes you know JavaScript closures, function components, useState, and basic useEffect. Earlier chapters showed that a ref survives renders without causing them. Here you apply that to timers, subscriptions, and similar "instance values".
What counts as a non-visual value
Some data a component needs does not appear in its JSX. Examples:
- A timer ID returned by
setIntervalorsetTimeout. - An
AbortControllerfor a request in flight. - A WebSocket or other connection object.
- A counter of how many times something happened, used only for logic.
- A flag such as "the user has already been warned".
- The previous value of a prop, kept for comparison.
If changing the value would not change what the user sees, re-rendering is wasted work. A ref stores the value and skips the render. Class components kept these on this, so people call them instance values. A ref plays the same role in a function component.
Why a plain variable does not work
A function component runs again on every render. A variable declared inside it is recreated each time.
import { useState } from 'react';
export function BrokenTimer() {
const [, setTick] = useState(0);
let timerId = null; // reset to null on every render
function start() {
timerId = setInterval(() => setTick((t) => t + 1), 1000);
}
function stop() {
clearInterval(timerId); // after a re-render this is null, so nothing stops
}
return (
<>
<button onClick={start}>Start</button>
<button onClick={stop}>Stop</button>
</>
);
}After the first tick, the component re-renders and timerId is null again. The stop function from the new render clears nothing, and the interval keeps running.
A variable declared outside the component survives, but all instances of the component share it. Two timers on one page would overwrite each other's ID. A ref gives you a separate persistent slot for each component instance.
The stopwatch example
The stopwatch below keeps the displayed seconds in state and the interval ID in a ref.
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 what each part does:
secondsis state because it appears in the JSX. Each tick must trigger a render so the number updates.intervalRefis a ref because the ID is never displayed. SettingintervalRef.currentdoes not cause a render.startchecksintervalRef.current !== nullfirst. Without that guard, clicking Start twice would create two intervals and lose the ID of the first. The stopwatch would then count at double speed and Stop could cancel only one of them.stopclears the interval and resets the ref tonull. Resetting is what lets the guard instartwork later.- The effect with an empty dependency array returns a cleanup function. It runs when the component unmounts, so a running timer does not keep calling
setSecondson a component that is gone.
The interval callback uses setSeconds((s) => s + 1), the updater form. The callback was created during one render and closes over that render's seconds. The updater form avoids reading that stale value.
Where you write to a ref
The timer ref is written in event handlers (start, stop) and read in a cleanup function. None of that happens during rendering. This matches the rule from the next chapter: read and write ref.current in event handlers and effects, not in the body of the component.
The diagram shows the flow of the stopwatch.
Other values worth keeping in a ref
Timeouts for debouncing
A debounce waits until the user pauses before acting. The pending timeout ID has to survive between keystrokes so the next keystroke can cancel it.
import { useEffect, useRef, useState } from 'react';
export function DebouncedSearch({ onSearch }) {
const [text, setText] = useState('');
const timeoutRef = useRef(null);
function handleChange(event) {
const value = event.target.value;
setText(value);
clearTimeout(timeoutRef.current);
timeoutRef.current = setTimeout(() => onSearch(value), 400);
}
useEffect(() => {
return () => clearTimeout(timeoutRef.current);
}, []);
return <input value={text} onChange={handleChange} placeholder="Search" />;
}clearTimeout(null) is harmless, so no guard is needed before the first call. The text is state because the input displays it. The timeout ID is a ref because nothing displays it.
Cancelling requests
An AbortController is another object you create once per request and may need to cancel later. Keeping it in a ref lets a later event handler abort the earlier request.
import { useEffect, useRef, useState } from 'react';
export function UserLoader({ userId }) {
const [name, setName] = useState('');
const controllerRef = useRef(null);
useEffect(() => {
controllerRef.current?.abort();
const controller = new AbortController();
controllerRef.current = controller;
fetch(`/api/users/${userId}`, { signal: controller.signal })
.then((res) => res.json())
.then((user) => setName(user.name))
.catch((error) => {
if (error.name !== 'AbortError') console.error(error);
});
return () => controller.abort();
}, [userId]);
return <p>{name}</p>;
}Here the effect's own cleanup already aborts the request, so the ref is optional. It becomes necessary when you want to abort from outside the effect, for example from a Cancel button's click handler.
Counters and flags
A ref also works for a number or boolean used only in logic.
import { useRef } from 'react';
export function WarnOnce({ onWarn }) {
const warnedRef = useRef(false);
function handleClick() {
if (warnedRef.current) return;
warnedRef.current = true;
onWarn();
}
return <button onClick={handleClick}>Delete</button>;
}If the user interface should change after the warning, for example by showing a message, the flag is no longer non-visual. Use state instead.
Ref or state for these values
Use this test: if the user would see a different screen when the value changes, use state. Otherwise a ref is a candidate.
| Value | Shown on screen? | Use |
|---|---|---|
| Elapsed seconds | Yes | State |
| Interval ID | No | Ref |
| Search text in a controlled input | Yes | State |
| Pending debounce timeout ID | No | Ref |
| Loading spinner flag | Yes | State |
| In-flight `AbortController` | No | Ref |
A ref is not a way to avoid re-renders for data that matters visually. If you put the seconds in a ref, the stopwatch would count internally while the screen stayed at 0.
Edge cases and gotchas
- Strict Mode in development. React runs effects, cleanup, then effects again on mount. Cleanup must therefore be safe to run and leave the ref in a usable state. Clearing an interval and setting the ref back to
nullhandles this. - Cleanup reads the latest value. In the stopwatch, the cleanup function reads
intervalRef.currentwhen it runs, which is the current ID. That is what you want for timers. For DOM refs, linters warn thatref.currentmay have changed by cleanup time. For timer IDs the warning does not apply because you want the latest value. - Resetting to
nullmatters.clearIntervalstops the timer but does not change your ref. If you skipintervalRef.current = null, a guard like!== nullwill wrongly believe the timer is still running. - Two writers. If several handlers can set the same ref, the order of events decides the result. Keep writes in few places.
- Refs are not shared between instances. Each mounted copy of the component has its own ref. If two components must share a value, lift state up or use a module-level variable on purpose.
- Changing a ref does not update the screen. If you log
ref.currentand it looks right but the UI is stale, the value probably belongs in state.
Summary of the pattern
- Create the ref with
useRef(null)or another starting value. - Write to it in event handlers or effects when the timer, request, or flag is created.
- Read it in event handlers or effects when you need to cancel or check it.
- Clear the resource and reset the ref when stopping.
- Return a cleanup function from an effect so unmounting stops the resource.
Exercise
A component starts a setTimeout in a click handler and stores the ID in a ref named timeoutRef. The user clicks the button twice quickly. What should the handler do before starting the second timeout, and why? Also, why is the ID a ref rather than state?
Show answer
Call clearTimeout(timeoutRef.current) before assigning the new ID. Otherwise the first timeout's ID is overwritten and can never be cancelled, so both timeouts fire. The ID is a ref because the screen does not display it, so changing it does not need a re-render.
Exercise
In the stopwatch, stop calls clearInterval(intervalRef.current) but you remove the line intervalRef.current = null. Describe what goes wrong when the user clicks Stop and then Start.
Show answer
After Stop, intervalRef.current still holds the old ID, so the guard if (intervalRef.current !== null) return; in start exits early. The interval never restarts and the stopwatch stays frozen.
Exercise
You want to show a "Recording..." label while a timer runs. Should "is recording" be a ref or state? Name the fix if you used a ref and the label never appeared.
Show answer
It should be state, because the label is visible. If a ref was used, changing it does not trigger a render, so the label does not update. Replace it with useState and set it in start and stop. The interval ID can stay in a ref.