Sub topic 3
Ref or state: how to decide
This chapter assumes you know JavaScript closures, React function components, useState, and basic useEffect. It covers one question: when a value changes, should it live in state or in a ref?
The core difference
State and refs both keep a value between renders. They differ in what happens when the value changes.
- Setting state schedules a re-render, and the new value shows up in the next render's output.
- Changing
ref.currentdoes nothing visible. React does not notice, and the screen stays the same until something else causes a render.
The decision follows from that difference. If the screen must update when the value changes, use state. If the value only needs to be remembered, use a ref.
A decision test
Ask these questions in order:
- Does the user see this value, or does it decide what the user sees? If yes, use state.
- Is the value read during rendering? If yes, use state. Reading
ref.currentin render gives results that can be stale. - Does changing it need to trigger a render? If yes, use state.
- Is it only read in event handlers, effects, or timers? If yes, a ref is a good fit.
Worked example: the stopwatch
A stopwatch holds two values, and each one lands on a different side of the test.
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>
);
}secondsis displayed, so it is state. Each tick must produce a new render.- The interval ID is never displayed. Only
start,stop, and the cleanup function read it, so a ref works. Storing it in state would cause an extra render each time you start or stop, with no visible change.
The ref also solves a problem state could not. stop needs the ID of the interval that start created, possibly many renders earlier. A ref always points to the same container, so stop reads the current ID.
What goes wrong when you choose badly
| Mistake | Symptom | Fix |
|---|---|---|
| Displayed value kept in a ref | Value changes, but the screen does not update | Move it to state |
| Non-visual value kept in state | Extra renders and sometimes stale values inside timers | Move it to a ref |
| Ref read during render | Output depends on a value React does not track | Read it in a handler or effect, or use state |
A quick comparison
| Row | State | Ref |
|---|---|---|
| Persists across renders | Yes | Yes |
| Changing it triggers a render | Yes | No |
| Safe to read during render | Yes | No |
| How to update | Setter function | Assign to `ref.current` |
| Typical uses | Visible data, form values | Timer IDs, DOM nodes, previous values |
Exercise
A component counts how many times a user clicked a button, and shows "Clicked N times" on screen. A teammate stores the count in a ref and increments countRef.current in the click handler. The text never changes. Why, and what is the fix?
Show answer
Changing ref.current does not trigger a re-render, so React never renders the new count. The count appears on screen, so it belongs in state. Replace the ref with const [count, setCount] = useState(0) and call setCount(c => c + 1) in the handler.
Exercise
You want to log how many times a user clicked a button when the component unmounts. The count is never shown on screen. Should it be state or a ref, and why?
Show answer
A ref. The value is not displayed and not read during render, so re-rendering on every click would be wasted work. Increment countRef.current in the handler and read it in the effect cleanup.