Sub topic 12
Lazy initialization of ref contents
This chapter assumes you know useRef basics, the rule against reading or writing ref.current during rendering, and how useState and useEffect work. It covers the one case where React allows you to touch ref.current while rendering. That case is creating an expensive value once.
The cost hidden in `useRef(initialValue)`
useRef(initialValue) uses its argument only on the first render. On later renders React ignores it and returns the same object. The argument is still evaluated on every render, though. JavaScript computes it before useRef is called.
import { useRef } from 'react';
class Tracker {
constructor() {
console.log('Tracker created');
this.events = [];
}
add(name) {
this.events.push(name);
}
}
export function Wasteful() {
const trackerRef = useRef(new Tracker());
return (
<button
onClick={() => {
trackerRef.current.add('click');
console.log(trackerRef.current.events.length);
}}
>
Track a click
</button>
);
}The component works. The ref keeps the first Tracker, and the event count grows as you click. But new Tracker() runs on every render, and every instance after the first is thrown away. With a cheap constructor you will never notice. With an expensive one, such as parsing a large file, building a big lookup table, or allocating a canvas buffer, every render pays for work that is then discarded.
The lazy initialization pattern
Start the ref with null and create the value only when the ref is still empty.
import { useRef } from 'react';
class Tracker {
constructor() {
console.log('Tracker created');
this.events = [];
}
add(name) {
this.events.push(name);
}
}
export function Efficient() {
const trackerRef = useRef(null);
function getTracker() {
if (trackerRef.current === null) {
trackerRef.current = new Tracker();
}
return trackerRef.current;
}
return (
<button
onClick={() => {
getTracker().add('click');
console.log(getTracker().events.length);
}}
>
Track a click
</button>
);
}getTracker creates the Tracker the first time anyone asks for it and returns the same instance afterward. The constructor runs once for the life of the component instance, not once per render.
A small getter function is the usual shape. It keeps the null check in one place, so no caller can forget it. The same helper works from event handlers, effects, and the render body.
Why this is allowed during rendering
The earlier rule says not to read or write ref.current while rendering, because the result would depend on something React does not track. Lazy initialization is the documented exception, and it is safe for a specific reason. The write happens only when the ref is empty, and it always stores the same kind of value. Whatever the number of renders or the order they run in, the outcome is identical: the ref holds one instance of the value. The render stays predictable.
Keep the creation step pure
The creation code runs during rendering, so hold it to the same standard as any render code.
- It should not subscribe to anything, start timers, open connections, or touch the DOM.
- It should not depend on values that change between renders, since it runs only once and the result will go stale.
- It should be safe to run more than once. In development, React's Strict Mode calls component bodies twice to expose impure code. In concurrent rendering, React can also start a render and abandon it. A lazy initializer might therefore run for a render that never commits.
Anything with a side effect belongs in an effect, where setup and cleanup are paired.
import { useEffect, useRef } from 'react';
class Meter {
constructor() {
this.samples = [];
this.timerId = null;
}
start() {
this.timerId = setInterval(() => {
this.samples.push(performance.now());
}, 1000);
}
stop() {
clearInterval(this.timerId);
this.timerId = null;
}
}
export function Sampler() {
const meterRef = useRef(null);
if (meterRef.current === null) {
meterRef.current = new Meter(); // pure: no timers started here
}
useEffect(() => {
const meter = meterRef.current;
meter.start(); // side effect lives in the effect
return () => meter.stop();
}, []);
return <p>Sampling in the background</p>;
}The constructor only sets up plain fields, which is safe if React discards a render. The interval starts in useEffect and is cleared in its cleanup. Calling meter.start() in the render body would leak a timer every time React repeated or abandoned a render.
When `null` is a real value
The === null check assumes null means "not created yet". If null or undefined could be a legitimate stored value, the check will keep re-running your creation code. Use a sentinel that cannot collide with real data.
import { useRef } from 'react';
const UNSET = Symbol('unset');
function findConfig() {
// Imagine this is slow and may legitimately return null.
return null;
}
export function ConfigReader() {
const configRef = useRef(UNSET);
function getConfig() {
if (configRef.current === UNSET) {
configRef.current = findConfig();
}
return configRef.current;
}
return <p>{getConfig() === null ? 'No config found' : 'Config loaded'}</p>;
}Here the result of findConfig() may be null, and that is a finished result. Because the ref starts as UNSET, a stored null is never mistaken for "not yet computed". Define the symbol at module level so that it is the same object on every render.
Alternatives and how they compare
React has other tools that can hold an expensive value. Each has different guarantees.
| Approach | Computed once? | Can change later? | Notes |
|---|---|---|---|
| `useRef(new X())` | No, evaluated every render | Yes, by assignment | Only the first result is kept. The rest is wasted work. |
| `useRef(null)` plus a getter | Yes | Yes, by assignment | Manual pattern. Changing it does not re-render. |
| `useState(() => new X())` | Yes, initializer runs on mount | Only through the setter, which re-renders | Built-in lazy form. Use it when the value is tied to what the screen shows. |
| `useMemo(() => new X(), [])` | Usually, but not guaranteed | No | React may discard cached values. Treat it as an optimization, not a promise. |
| Module-level constant | Once per page load | Yes | Shared by every component instance. Not suitable when each instance needs its own copy. |
Two of these are worth a closer look.
useState(() => new X()) also runs your function only once. If you never call the setter, it behaves like a lazily built constant and you can ignore the second element of the returned pair. Many teams prefer it for this reason, because the lazy behavior is built into React rather than hand-written. Choose a ref when the instance may be replaced later without a re-render, such as swapping in a new player object, or when the value is a mutable holder like a Map. Choose state when the value affects the output.
useMemo is not a good home for a value that must stay the same. The React documentation describes memoization as a performance hint, and React may drop the cache and recompute. If identity matters, for example because the object holds a connection, use a ref or state.
Common mistakes
- Writing
useRef(new X())and assuming it is lazy. The argument is evaluated on every render. Only the stored result is reused. - Initializing in an unguarded render statement.
ref.current = new X()without thenullcheck replaces the value on every render and defeats the purpose of a ref. - Starting side effects in the initializer. Timers and subscriptions created there can leak or duplicate. Put them in an effect with cleanup.
- Reading the ref for display after lazy creation. If the value is shown on screen, changing it will not update the screen. This is the signal to use state instead.
- Forgetting the
nullcase in handlers. ReadingtrackerRef.current.add(...)directly in a handler is only safe if something has already initialized it. Going through the getter avoids the question.
Exercise
A component declares const cacheRef = useRef(buildLargeIndex(data));. The component renders often, and profiling shows buildLargeIndex runs on every render even though the ref keeps its first value. Rewrite the code so the index is built only once, and say why the original is slow. Also say what you would change if buildLargeIndex could legitimately return null.
Show answer
The argument to useRef is evaluated on every render. React ignores it after the first render, but the work has already been done. Rewrite it as const cacheRef = useRef(null); with a getter: function getIndex() { if (cacheRef.current === null) { cacheRef.current = buildLargeIndex(data); } return cacheRef.current; }. Use getIndex() wherever the index is needed. If buildLargeIndex can return null, start the ref with a module-level sentinel such as const UNSET = Symbol('unset');, create the ref with useRef(UNSET), and compare against UNSET instead of null. Otherwise a stored null result would trigger the computation again on every call. The index is also captured from the data of the first render, so if data changes and the index must follow it, a ref is the wrong tool and useMemo keyed on data fits better.