Sub topic 7
Don't touch ref.current while rendering
This chapter assumes you know JavaScript closures, React function components, useState, and basic useEffect. You have seen that useRef returns an object with a current property that persists across renders. Here you learn when it is safe to read and write that property.
Why rendering must be pure
React calls your component function to work out what the screen should look like. That call must behave like a calculation: the same props and state produce the same JSX, and nothing outside the function changes.
React relies on this. It may call a component more than once, pause a render, or throw one away. In development, Strict Mode deliberately renders twice to expose impure code.
A ref is a mutable box. React does not track changes to ref.current, so a write during render is a side effect that nothing coordinates. A read is just as risky, because the value can change between renders without React knowing.
What goes wrong
This component counts renders by writing to a ref during render:
import { useRef } from 'react';
export function Counter() {
const renders = useRef(0);
renders.current += 1; // write during render: impure
return <p>Rendered {renders.current} times</p>;
}The result is unreliable. Strict Mode double-renders, so the count jumps by two. A render that React discards still increments the counter. The displayed number does not match what actually reached the screen.
Reading has a similar problem. If the JSX depends on ref.current, the output can go stale, because changing a ref never schedules a new render.
Where to read and write instead
Use ref.current in places that run after React has committed the render, or in response to something the user did.
| Place | Read or write `ref.current`? |
|---|---|
| Top level of the component body | No |
| Event handlers | Yes |
| `useEffect` and its cleanup | Yes |
| Callback refs | Yes, to store the node |
| Lazy initialization (`if (ref.current === null)`) | Yes, the one render-time exception |
Here is the render counter done safely, with the write moved into an effect:
import { useEffect, useRef, useState } from 'react';
export function Counter() {
const [count, setCount] = useState(0);
const clicks = useRef(0);
function handleClick() {
clicks.current += 1; // event handler: safe
setCount(count + 1);
}
useEffect(() => {
console.log('Clicks so far:', clicks.current); // effect: safe
});
return <button onClick={handleClick}>Clicked {count} times</button>;
}The value shown on screen comes from state. The ref holds a side value that only handlers and effects touch.
The lazy initialization exception
You may write to a ref during render when you are filling an empty ref once. The check makes the write idempotent, so repeated renders give the same result:
import { useRef } from 'react';
function createExpensiveObject() {
return { createdAt: Date.now() };
}
export function Example() {
const objRef = useRef(null);
if (objRef.current === null) {
objRef.current = createExpensiveObject();
}
return <p>Created at {objRef.current.createdAt}</p>;
}Writing useRef(createExpensiveObject()) would also work, but it calls the function on every render and throws the result away after the first one.
Exercise
A component contains const clicks = useRef(0); and then renders <p>{clicks.current}</p>, with a button whose handler does clicks.current += 1. Clicking the button does not change the text. Why, and what is the fix?
Show answer
Changing ref.current does not trigger a re-render, so the JSX never runs again and the text stays stale. Reading ref.current during render is also unsafe. Since the number appears on screen, store it in state with useState and update it with the setter.