Sub topic 3
Ref or state: how to decide
This chapter assumes you know JavaScript closures, React function components and JSX, useState and re-rendering, and basic useEffect. Earlier chapters covered what useRef returns and why its value survives renders. Here the question is which of the two tools fits a given piece of data.
The core difference
State and refs both persist between renders. They differ in what happens when you change them.
- Calling a state setter schedules a re-render. React runs your component again, and the new value appears in the output.
- Assigning to
ref.currentchanges the value immediately and tells React nothing. No re-render happens, and the screen does not update.
A ref is a plain object, { current: value }, that React keeps for the lifetime of the component. React never watches it. State is a snapshot tied to a render, and a ref is a mutable box that every render shares.
| Property | `useState` | `useRef` |
|---|---|---|
| Returns | `[value, setValue]` | `{ current: value }` |
| Changing it triggers a re-render | Yes | No |
| Update is visible | In the next render | Immediately, on the same object |
| Safe to read during rendering | Yes | No, except for lazy initialization |
| Safe to write during rendering | No, except derived-state patterns | No, except for lazy initialization |
| Typical contents | Anything shown on screen | Timer IDs, DOM nodes, values not shown |
A decision rule
Ask one question: does this value affect what the component renders?
- If yes, use state. React must know about the change so it can update the screen.
- If no, a ref is a good fit, because changing it needs no re-render.
Rendering includes more than visible text. A value that decides which class name, which branch of JSX, or which child props are produced affects rendering, even if it looks like internal bookkeeping.
The third branch matters. A value that is only needed during one render, or one event handler call, belongs in a plain variable. Reach for a ref only when the value has to outlive a render.
A worked comparison: a click counter
Suppose you want to count button clicks. Here is the ref version:
import { useRef } from 'react';
export function RefCounter() {
const count = useRef(0);
function handleClick() {
count.current += 1;
console.log('Clicked', count.current, 'times');
}
return (
<>
<p>Count shown: {count.current}</p>
<button onClick={handleClick}>Click</button>
</>
);
}The console log increases on every click, but the paragraph stays at 0. The ref changed, and React was never told, so it never re-rendered. The paragraph would show a new number only if something else caused a render. That is a bug waiting to happen, because the text is then stale in a way that depends on unrelated updates.
The count is displayed, so it belongs in state:
import { useState } from 'react';
export function StateCounter() {
const [count, setCount] = useState(0);
return (
<>
<p>Count shown: {count}</p>
<button onClick={() => setCount(count + 1)}>Click</button>
</>
);
}Now each click re-renders, and the paragraph always matches the data.
When a ref is the better choice
Consider a stopwatch. The displayed seconds are state. The interval ID returned by setInterval is something you need later, to cancel the timer, but you never draw it on screen.
import { 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;
}
return (
<div>
<p>{seconds}s</p>
<button onClick={start}>Start</button>
<button onClick={stop}>Stop</button>
</div>
);
}If the interval ID were state, every start and stop would cause an extra render that changes nothing visible. A plain let variable would not work either. Each render creates a new variable, so stop would see undefined after the first re-render caused by setSeconds. The ref gives you a value that persists and costs nothing to update.
Note that this version leaves out the unmount cleanup. A later chapter covers refs inside effects, where you will add it.
Why you cannot just use a variable
A variable declared in the component body is recreated on every render. A variable declared at module level persists, but it is shared by every instance of the component. Two stopwatches on one page would overwrite each other's interval ID.
| Storage | Survives re-renders | Separate per component instance | Triggers re-render |
|---|---|---|---|
| Local variable | No | Yes | No |
| Module-level variable | Yes | No | No |
| `useRef` | Yes | Yes | No |
| `useState` | Yes | Yes | Yes |
A ref is the only option that is both per-instance and silent.
Edge cases and gotchas
Reading a ref can give stale or surprising results
State read inside an event handler is a snapshot from the render that created the handler. A ref always reads the current value. This sometimes looks like an advantage, and sometimes it hides a design problem.
import { useRef, useState } from 'react';
export function DelayedAlert() {
const [text, setText] = useState('');
const latest = useRef('');
function handleChange(e) {
setText(e.target.value);
latest.current = e.target.value;
}
function handleSend() {
setTimeout(() => {
alert(`State: "${text}", ref: "${latest.current}"`);
}, 3000);
}
return (
<>
<input value={text} onChange={handleChange} />
<button onClick={handleSend}>Send in 3 seconds</button>
</>
);
}If you click Send and then keep typing, the alert shows the text as it was at click time for state, and the newest text for the ref. Which behavior is correct depends on your intent. For a message the user meant to send at click time, the state snapshot is correct. Using a ref to dodge snapshots only makes sense when you truly want the latest value. Do not switch to a ref just because the state value looks old.
Do not mirror state in a ref by default
Copying state into a ref "to avoid re-renders" does not avoid them. The setText call above still renders. You end up with two copies of the same value that can drift apart. Keep one source of truth, and use the second copy only when a specific need, such as reading the latest value inside a long-lived callback, requires it.
A ref that drives the UI is a bug
If you find yourself writing ref.current = x and then wondering why the screen did not change, the value belongs in state. The reverse also happens. If you add state for a value and find that your effect runs or your component re-renders on every tiny change with no visible result, such as a mouse position that you only read on click, consider a ref.
Mixing both in one update
Some features need both. A drag interaction might store the starting pointer position in a ref, since nothing displays it, and the current offset in state, since the element must move on screen. Split the data by this rule, one value at a time. There is no need to pick a single tool for the whole component.
Summary of the rule
Use state for data that appears in the output. Use a ref for data that React does not need to know about but that must persist across renders. Use a local variable for anything that does not need to persist. When unsure, start with state. It is the safer default because the screen can never fall out of sync with it, and moving a value to a ref later is a small change.
Exercise
A component tracks how many times a user has clicked "Like" and shows the number next to the button. A second value records the timestamp of the last click, which is sent to an analytics service and never displayed. Which of the two values should be state, which should be a ref, and why?
Show answer
The click count should be state, because it appears in the output and the screen must update when it changes. The last-click timestamp should be a ref, because nothing rendered depends on it. Updating it in the click handler needs no re-render, and a ref keeps the value across renders for each component instance.
Exercise
A developer writes const timerId = useRef(null) and sets timerId.current = setTimeout(...) in a handler. A teammate suggests replacing it with useState "to be safe." Name one cost of that change and one problem a plain let timerId in the component body would cause.
Show answer
With state, each assignment causes an extra re-render that changes nothing on screen. With a plain let inside the component, the variable is recreated on every render, so a later handler or a re-rendered closure sees a fresh undefined instead of the stored timer ID, and the timer cannot be cancelled.