Sub topic 7
Don't touch ref.current while rendering
This chapter assumes you know useState and re-rendering, the basics of useEffect, and the useRef API from earlier chapters. You should also know that a ref is an object shaped like { current: value } that React keeps between renders.
Why rendering must be pure
React calls your component function to work out what the screen should look like. That call is the render. A component should behave like a formula: the same props, state, and context must always produce the same JSX. React relies on this in several ways:
- In development, Strict Mode renders every component twice to expose impure code.
- With concurrent rendering, React may start a render, pause it, and throw it away without ever showing it.
- React may skip a render entirely, or reuse an earlier result.
State follows these rules. It is a snapshot for each render, and React controls when it changes. A ref is different. Its current property is a plain mutable property, and React does not track it. If you change it while rendering, you make a side effect that React can't undo or predict.
What goes wrong when you write during render
Here is a component that counts its own renders:
import { useRef } from 'react';
export function RenderCounter() {
const renders = useRef(0);
renders.current += 1; // write during render
return <p>Rendered {renders.current} times</p>;
}This looks harmless, but it has three problems.
- In development with Strict Mode, the first mount shows
2, because React ran the function twice and the ref was mutated both times. - If React discards a render, the counter still increased. The number no longer matches what the user saw.
- The number is not tied to anything on screen, so you can't reason about it.
Reading has a related problem:
import { useRef } from 'react';
export function ClickCounter() {
const clicks = useRef(0);
return (
<>
<button onClick={() => { clicks.current += 1; }}>Click</button>
<p>Clicks: {clicks.current}</p>
</>
);
}The handler changes the ref, but nothing asks React to render again. The paragraph keeps showing 0 until something else triggers a render. Then it jumps to the current value. The screen is now out of step with your data.
Both examples break the same rule. If the value appears on screen, it belongs in state:
import { useState } from 'react';
export function ClickCounter() {
const [clicks, setClicks] = useState(0);
return (
<>
<button onClick={() => setClicks(clicks + 1)}>Click</button>
<p>Clicks: {clicks}</p>
</>
);
}Where it is safe to use ref.current
The safe places are the ones React runs outside of rendering:
| Location | Read `ref.current` | Write `ref.current` |
|---|---|---|
| Event handlers (`onClick`, `onChange`) | Yes | Yes |
| Effects (`useEffect`, `useLayoutEffect`) and their cleanup | Yes | Yes |
| Timer and subscription callbacks started from handlers or effects | Yes | Yes |
| Directly in the component body, during render | No | No, except lazy initialization |
The diagram also explains a common error. A DOM ref is null during the first render, because the node does not exist yet. React sets ref.current during the commit phase, so reading it in the component body gives null on mount:
import { useEffect, useRef } from 'react';
export function Measured() {
const boxRef = useRef(null);
// Wrong: boxRef.current is null on the first render.
// const width = boxRef.current.offsetWidth;
useEffect(() => {
// Right: the node exists after commit.
console.log(boxRef.current.offsetWidth);
}, []);
return <div ref={boxRef}>Box</div>;
}The one exception: lazy initialization
Some values are expensive to create. If you write useRef(createIndex()), the call to createIndex() runs on every render, even though useRef only uses the result the first time. The fix is to start the ref at null and fill it in during render, but only once:
import { useRef } from 'react';
class SearchIndex {
constructor() {
this.items = new Map();
}
add(key, value) {
this.items.set(key, value);
}
get(key) {
return this.items.get(key);
}
}
export function Lookup({ keyName }) {
const indexRef = useRef(null);
if (indexRef.current === null) {
indexRef.current = new SearchIndex();
indexRef.current.add('a', 'Apple');
indexRef.current.add('b', 'Banana');
}
return <p>{indexRef.current.get(keyName) ?? 'Not found'}</p>;
}This is allowed because the result does not depend on when or how often it runs. If React renders twice and throws one result away, the second run builds an equivalent object. The check === null guarantees that later renders never write to the ref again. React's own documentation calls this out as an accepted exception.
Keep the exception narrow:
- Initialize only when the value is
null. - Always produce the same kind of value, with no dependence on randomness, the current time, or props that change.
- Don't use it to update a ref on later renders.
If the setup is cheap, useRef(new Set()) is simpler and fine. If the object must be recreated when a prop changes, it is not a ref.
Writing the latest value: use an effect
A frequent mistake is keeping the newest prop or callback in a ref by assigning it in the body:
import { useRef } from 'react';
export function useLatest(value) {
const ref = useRef(value);
ref.current = value; // write during render
return ref;
}It usually works, but it writes during render. If React discards that render, the ref holds a value for a UI the user never saw, and other code (such as an interval callback) may use it. Move the write into an effect, which only runs for renders that were committed:
import { useEffect, useRef } from 'react';
export function useLatest(value) {
const ref = useRef(value);
useEffect(() => {
ref.current = value;
});
return ref;
}The effect has no dependency array, so it runs after every committed render. That is intentional here, because the goal is to always hold the latest value. The useInterval hook you have seen uses the same structure.
Derived values from refs
Sometimes you want something computed from a ref, such as "the previous value of this prop." The popular usePrevious hook writes in an effect and reads during render:
import { useEffect, useRef } from 'react';
export function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current; // read during render
}It works in practice, but the read during render is the pattern this chapter warns against. The result depends on mutable data that React doesn't track. For anything that affects what the user sees, prefer state:
import { useState } from 'react';
export function PriceTag({ price }) {
const [prevPrice, setPrevPrice] = useState(price);
const [trend, setTrend] = useState('same');
if (price !== prevPrice) {
setTrend(price > prevPrice ? 'up' : 'down');
setPrevPrice(price);
}
return <p>{price} ({trend})</p>;
}Calling a set function during render is allowed in one narrow case: updating the component's own state, guarded by a condition so it settles. React then re-renders right away, before showing anything.
A quick checklist
When you see ref.current in a component body, ask:
- Is it inside a handler, an effect, or a callback started by one? If so, it is fine.
- Is it the
if (ref.current === null)lazy initialization? If so, it is fine. - Does the value show on screen? Use state.
- Is it a DOM node? Wait until after mount, in an effect or a handler.
- Is it holding the latest prop? Assign it in an effect.
Exercise
A teammate writes const lastQuery = useRef(''); lastQuery.current = query; in the component body and reads lastQuery.current inside a setTimeout callback started from a click handler. What is the risk, and how do you fix it?
Show answer
The write happens during render. If React discards or repeats that render, the ref can hold a value from a render that was never committed. Move the assignment into useEffect(() => { lastQuery.current = query; }); so it only runs after a committed render. The read in the timeout callback is already safe.
Exercise
This component should show how many times the user has clicked "Add", but the number lags behind. Why, and what is the fix? const count = useRef(0); return <button onClick={() => { count.current++; }}>Add ({count.current})</button>;
Show answer
Changing count.current does not trigger a re-render, so the label only updates when something else causes a render. The count appears on screen, so it should be state: const [count, setCount] = useState(0); with onClick={() => setCount(count + 1)}.