Sub topic 2
A value that survives renders without causing them
This chapter explains how useRef keeps a value between renders without causing a render. It assumes you know JavaScript closures, function components and JSX, useState and re-rendering, and basic useEffect. The next chapter covers how to choose between a ref and state. This one covers the mechanism that makes the choice possible.
The problem a ref solves
A function component runs again on every render. Anything you declare inside it with let or const is created fresh each time. State is the usual way to keep a value between renders, but setting state always schedules another render.
Sometimes you need a value that persists and that you can change without touching the screen. Examples are a count of clicks for logging, an ID returned by setTimeout, or the previous value of a prop. A ref fits these cases.
What useRef gives you
useRef(initialValue) returns a plain object with one property:
{ current: initialValue }React creates this object on the first render and returns the same object on every later render of that component instance. The argument is only used the first time. Later calls ignore it.
You can read and write current freely. React does not watch it. Writing to current does not notify React and does not schedule a render.
import { useRef } from 'react';
export function ClickTally() {
const clicks = useRef(0);
function handleClick() {
clicks.current = clicks.current + 1;
console.log(`Clicked ${clicks.current} times`);
}
return <button onClick={handleClick}>Click me</button>;
}Each click increments the stored number and logs it. The button's output never changes, and the component does not re-render. The count still survives, because each click handler sees the same clicks object.
Why the value persists
Two facts explain the behavior.
- React stores the ref object alongside the component instance, in the same internal slot list that holds state. The nth
useRefcall in a component always maps to the nth slot, which is why hooks must be called in the same order every render. - Because the object is the same one each time, a mutation made during one render's event handler is visible to the next render, and to every closure that captured the object.
The second fact matters most. A closure captures the ref object, not a snapshot of current. Reading ref.current inside a callback returns whatever the value is at that moment.
Comparing a local variable, state, and a ref
The component below holds the same counter in three places. Pressing the button updates all three, and it also sets state, so the component re-renders.
import { useRef, useState } from 'react';
export function Compare() {
const [stateCount, setStateCount] = useState(0);
const refCount = useRef(0);
let localCount = 0;
function handleAdd() {
localCount += 1;
refCount.current += 1;
setStateCount(stateCount + 1);
console.log(
`local: ${localCount}, ref: ${refCount.current}, state in this render: ${stateCount}`
);
}
return (
<div>
<p>State count: {stateCount}</p>
<button onClick={handleAdd}>Add</button>
</div>
);
}After three clicks the console shows:
local: 1, ref: 1, state in this render: 0
local: 1, ref: 2, state in this render: 1
local: 1, ref: 3, state in this render: 2localCountis always 1. Each render creates a new variable that starts at 0, and the handler from that render increments it once.refCount.currentkeeps growing because the object is shared across renders.stateCountinside the handler is the value from the render that created the handler. The new value arrives only in the next render.
The <p> shows state because state is what React renders. The ref value is not displayed. Showing it would mean reading current during rendering, which a later chapter explains is unsafe.
A ref is always current, state is a snapshot
State inside an event handler or timer callback is a snapshot from the render that created that function. A ref is a live pointer. This difference shows up whenever code runs later than the render.
import { useRef, useState } from 'react';
export function DelayedLog() {
const [count, setCount] = useState(0);
const countRef = useRef(0);
function handleIncrement() {
setCount(count + 1);
countRef.current += 1;
}
function handleLogLater() {
setTimeout(() => {
console.log(`state: ${count}, ref: ${countRef.current}`);
}, 3000);
}
return (
<div>
<p>Count: {count}</p>
<button onClick={handleIncrement}>Increment</button>
<button onClick={handleLogLater}>Log in 3 seconds</button>
</div>
);
}Click "Log in 3 seconds", then click "Increment" twice before the timer fires. The log prints state: 0, ref: 2. The timeout callback closed over the count from the render in which you pressed the log button, so it sees 0. It closed over the ref object, so it reads the value 2.
Neither result is wrong. A snapshot is what you want when the callback should act on the data the user saw. The live value is what you want when the callback should act on the newest data.
What a ref does and does not survive
The table compares four places to keep a value.
| Storage | Survives re-renders | Re-renders when changed | Separate per component instance | Reset when component unmounts |
|---|---|---|---|---|
| Local variable | No | No | Yes | Not applicable |
| State | Yes | Yes | Yes | Yes |
| Ref | Yes | No | Yes | Yes |
| Module-level variable | Yes | No | No, shared by all | No |
Two rows need care.
- A ref is per instance. If you render
<ClickTally />twice, each has its ownclicksobject. A module-level variable would be shared by both instances, and also by every user session in server rendering. - A ref does not outlive the component. When the component unmounts, its slots are discarded. Mounting it again, or changing its
key, creates a new ref with the initial value. If a value must survive unmounting, store it in state higher up in the tree, or in a store outside React.
Edge cases
The initial value is only used once
Changing the argument later has no effect.
import { useRef } from 'react';
export function Frozen({ start }) {
const startRef = useRef(start);
// startRef.current stays at the first `start` value,
// even if the parent passes a different `start` later.
return null;
}If you want a ref to follow a prop, you must assign to current yourself, outside rendering. The latest-callback pattern in a later chapter shows how.
The ref object is stable, so it never triggers effects
Because useRef returns the same object every render, putting it in an effect's dependency array has no effect. The lint rule for hooks knows this and does not require refs in dependency lists. Changing ref.current does not rerun any effect, since React does not observe it.
Mutating a ref does not update the screen
If you change ref.current and expect text on the page to change, nothing will happen. The page changes only when something else triggers a render, and then only if you rendered data that came from state or props. This is the most common surprise for people who first treat a ref like state.
Strict Mode and development double-running
In development, Strict Mode runs effects an extra time by simulating an unmount and remount. Refs keep their values through that simulation, so a ref holding a counter is not reset by it. Your code should still be safe if an effect that writes to a ref runs twice.
Writing during render
You can technically assign to ref.current while a component function runs. Do not. Render must be pure, and React may call it more than once or discard a render. Mutate refs in event handlers and effects. The one standard exception, lazy initialization, comes in a later chapter.
Summary of the working model
useRef(x)returns{ current: x }, and the same object comes back on every render of that instance.- Writing
currentis a plain JavaScript assignment. React does not see it and does not re-render. - Closures capture the object, so they always read the latest
current. State closures capture a snapshot. - Refs are per instance and are lost on unmount.
Exercise
A component declares const timesSeen = useRef(0); and a button handler runs timesSeen.current += 1; and nothing else. The JSX contains <p>Seen: {timesSeen.current}</p>. After five clicks, the text on screen still shows 0 (or a stale number). Why, and what is the smallest change that makes the displayed text correct?
Show answer
Changing timesSeen.current does not schedule a render, so React never re-runs the component and never updates the paragraph. Reading current in JSX is also discouraged, because rendering should depend only on props and state. The fix is to store the number in state, const [timesSeen, setTimesSeen] = useState(0), and call setTimesSeen(n => n + 1) in the handler. Use a ref only if the value never needs to appear on screen.
Exercise
A component sets a state value count, and also keeps a ref countRef updated to the same number in the click handler. A setTimeout started before two more clicks logs both values. Which one shows the newer number, and why?
Show answer
The ref shows the newer number. The timeout callback closed over the count variable from the render when the timer started, so it prints that old snapshot. It closed over the ref object itself, so countRef.current is read at the time the callback runs and returns the latest value.