Sub topic 1
What useRef returns
useRef is one of the smallest hooks in React, and it is often misread. This chapter covers what it returns and how that object behaves across renders. Later chapters build on that behavior for DOM access, timers, and effects.
Prerequisites
This chapter assumes you already know:
- JavaScript objects, closures, and functions, including the difference between a value and a reference to an object.
- React function components and JSX.
useStateand what a re-render is.- The basics of
useEffect. - Basic DOM concepts such as elements and focus.
The signature
const ref = useRef(initialValue);useRef takes one argument, the initial value. It returns a plain JavaScript object with a single property:
{ current: initialValue }That is the whole API. There is no setter function and no subscription. The current property is where you read and write the value.
You can put anything in it: a number, a string, an object, a function, or null. The name "ref" comes from its best-known use, which is holding a reference to a DOM node. The container itself does not care what it holds.
The same object on every render
A component function runs again on every render, and its local variables are created fresh each time. If you wrote const box = { current: 0 } in the component body, you would get a new object on every render. useRef returns the same object each time instead. React stores it with the component instance and hands it back.
The following component checks this. It saves the first ref object in a second ref, then compares the two in a click handler.
import { useRef, useState } from 'react';
export function RefIdentity() {
const [renders, setRenders] = useState(0);
const countRef = useRef(0);
const firstObject = useRef(countRef);
function handleClick() {
console.log('Same object as first render:', firstObject.current === countRef);
setRenders(renders + 1);
}
return <button onClick={handleClick}>Render again ({renders})</button>;
}Every click logs true. The argument to useRef(countRef) only matters on the first render, so firstObject.current keeps pointing at the object created then.
Each component instance gets its own ref. If you render <RefIdentity /> twice, the two copies have separate ref objects. Refs are not module-level variables.
Changing current does not cause a render
React re-renders a component when its state or props change, or when a parent renders it again. Writing to ref.current is a plain property assignment, and React does not observe it. Nothing is scheduled and the screen does not update.
The next component shows this. The first button changes the ref, and the second forces a render.
import { useRef, useState } from 'react';
export function RefVersusRender() {
const clicksRef = useRef(0);
const [, setTick] = useState(0);
return (
<div>
<p>Ref says: {clicksRef.current}</p>
<button
onClick={() => {
clicksRef.current += 1;
console.log('current is now', clicksRef.current);
}}
>
Add to ref
</button>
<button onClick={() => setTick((t) => t + 1)}>Force a render</button>
</div>
);
}Click "Add to ref" three times. The console logs 1, 2, 3, but the paragraph still says 0. Click "Force a render" and the paragraph jumps to 3. The value was updated the whole time. Only the rendered output was stale.
Updates are immediate
State updates are queued. Inside an event handler, the state variable keeps its old value until the next render. A ref is the opposite, because assignment takes effect at once:
import { useRef, useState } from 'react';
export function ImmediateVersusQueued() {
const [count, setCount] = useState(0);
const countRef = useRef(0);
function handleClick() {
setCount(count + 1);
countRef.current = countRef.current + 1;
console.log('state variable:', count);
console.log('ref value:', countRef.current);
}
return <button onClick={handleClick}>Clicked {count} times</button>;
}On the first click the log shows state variable: 0 and ref value: 1. The state variable is a snapshot of the render that created the handler. The ref is a live object that the handler reads when it runs.
This also means a ref gives you no snapshot guarantee. If an async callback reads ref.current after an await, it sees whatever value is there then, not the value from when the callback was created. That is sometimes what you want and sometimes a bug.
What happens across renders
The initial value is used once
useRef(initialValue) runs on every render, but React ignores the argument after the first one. Passing a new value later does not reset the ref.
import { useRef } from 'react';
export function IgnoredArgument({ startAt }) {
const ref = useRef(startAt);
return <p>{startAt}</p>;
}If the startAt prop changes from 5 to 10, ref.current stays 5. To follow a prop, write to the ref yourself from an effect or event handler.
The argument expression is still evaluated on each render. useRef(createBigStructure()) calls createBigStructure() every time and throws the result away after the first. For expensive setup, use the lazy initialization pattern from a later chapter instead.
Ref or state in one table
You will see this decision again in detail. For now, these are the properties that separate the two.
| Property | `useRef` | `useState` |
|---|---|---|
| Returns | A `{ current }` object | A value and a setter |
| Changing it triggers a render | No | Yes |
| Update timing | Immediate, mutable | Queued, snapshot per render |
| Safe to read during render | No, except for lazy initialization | Yes |
| Typical use | DOM nodes, timer IDs, other non-visual values | Anything shown on screen |
Lifetime and edge cases
- Unmount resets everything. A ref lives as long as its component instance. If the component unmounts and mounts again, you get a new ref object with the initial value. Changing the
keyof a component has the same effect. - Omitting the argument. In JavaScript,
useRef()gives{ current: undefined }. In TypeScript with React 19 types, the argument is required, so you writeuseRef(null)oruseRef<number>(0). - Identity is stable. You can use the ref object in a dependency array without causing the effect to rerun. ESLint's
react-hooksrules know thatuseRefresults are stable. The.currentvalue is not tracked, so do not put it in dependency arrays and expect it to trigger anything. - Development double rendering. In Strict Mode, React calls component functions twice in development to expose impure code. A component that writes to a ref while rendering will behave differently on those extra calls, which is one reason render-time writes are discouraged.
- Not shared across components. Two sibling components cannot see each other's refs unless you pass them down as props.
- You can replace
currentwith any value.ref.current = somethingElseis legal. The one exception is a ref you pass to a DOM element'srefattribute, where React managescurrentfor you. That is the next chapter's subject.
Common errors at this stage
- Expecting a render after a write. If the UI should change when the value changes, use state. A ref write alone will never update the screen.
- Writing
const [value, setValue] = useRef(0).useRefreturns an object, not a pair. Destructuring it as an array throws an error saying the value is not iterable. - Forgetting
.current.ref + 1produces a string like"[object Object]1". Useref.current + 1. - Recreating the object by hand. A plain
{ current: 0 }in the component body resets on each render. A module-levelletvariable persists but is shared by every instance and survives unmounts. Neither matches the per-instance, per-mount lifetime ofuseRef. - Expecting the argument to reset the ref. The argument is read once.
Exercise
A component calls const idRef = useRef(props.userId). The parent later passes a different userId, and the component re-renders. What does idRef.current hold, and how would you make it track the new prop?
Show answer
It still holds the original userId, because React ignores the argument to useRef after the first render. To track the prop, assign idRef.current = props.userId in an effect or an event handler. Do not assign it during rendering. If the new value should also change what the component displays, keep it in state or read the prop directly.
Exercise
In the RefVersusRender component, you click "Add to ref" twice and then click a third button that calls setOtherState('x') on an unrelated state variable. What does the paragraph show afterwards, and why?
Show answer
It shows 2. The click on the third button triggers a render, and the component reads clicksRef.current during that render. Any render picks up the current ref value, not only a render caused by the ref. The ref write itself never caused a render.