Sub topic 12
Lazy Initialization of Ref Contents
This chapter assumes you know useState, basic useEffect, and the rule that rendering must be pure. You should also know that useRef returns an object shaped like { current: value }.
The problem: an argument that runs every render
useRef(initialValue) only uses its argument on the first render. React ignores it afterward. But JavaScript still evaluates the expression you wrote on every render.
const mapRef = useRef(new Map());Every render builds a new Map, and React throws it away. For a Map this is cheap. For something expensive, such as a large table, a parser, or a Web Audio context, the wasted work adds up.
Unlike useState, useRef does not accept an initializer function. useRef(() => new Map()) would store the function itself as the value. You need a different approach.
The lazy pattern
Start the ref as null. Create the real value the first time you need it, then reuse it.
import { useRef } from 'react';
function useStore() {
const storeRef = useRef(null);
function getStore() {
if (storeRef.current === null) {
storeRef.current = new Map();
}
return storeRef.current;
}
return getStore;
}The Map is created once, on the first call to getStore(). Later calls return the same object.
Why writing during render is allowed here
Rendering should not read or write ref.current, because the result of a render could then depend on hidden, changing data. Lazy initialization is the one exception. The write is safe because:
- It only happens when the value is still
null. - Every render that reaches it produces the same result: a ref holding the created value.
- No other code observes the ref before it is filled.
The check and the assignment together make the operation idempotent. Running it twice gives the same state as running it once.
A worked example: the gallery
The gallery from the callback ref chapter keeps all its DOM nodes in a Map held by one ref. It uses the lazy pattern so the Map is created once.
import { useRef } from 'react';
export function Gallery({ items }) {
const nodesRef = useRef(null);
function getMap() {
if (nodesRef.current === null) {
nodesRef.current = new Map();
}
return nodesRef.current;
}
function scrollTo(id) {
getMap().get(id)?.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
return (
<>
<nav>
{items.map((item) => (
<button key={item.id} onClick={() => scrollTo(item.id)}>
{item.title}
</button>
))}
</nav>
<ul>
{items.map((item) => (
<li
key={item.id}
ref={(node) => {
const map = getMap();
if (node) {
map.set(item.id, node);
} else {
map.delete(item.id);
}
}}
>
{item.title}
</li>
))}
</ul>
</>
);
}getMap() is called from two places. The click handler calls it after rendering. Each callback ref calls it while React attaches nodes, which happens during the commit phase, not during render. In both cases the first call creates the Map and the rest reuse it.
Common mistakes
- Using
nullas a real value. The pattern relies onnullmeaning "not created yet." Ifnullis a valid value for your ref, use a different sentinel or a separate flag. - Wrapping the initializer in a function.
useRef(() => value)stores a function. Use thenullcheck instead. - Skipping the helper. Writing
ref.current.get(...)directly fails with aTypeErrorwhile the ref is stillnull. Go through the getter every time. - Using it for cheap values. For a number, a string, or an empty object, plain
useRef(value)is simpler and just as fast.
Exercise
Why does useRef(new ExpensiveParser()) waste work even though React only uses the argument on the first render, and how do you fix it?
Show answer
JavaScript evaluates new ExpensiveParser() on every render before calling useRef, so a new parser is built and discarded each time. Fix it by calling useRef(null) and creating the parser inside a helper that checks if (ref.current === null) before assigning ref.current = new ExpensiveParser().
Exercise
Why is it acceptable to write ref.current during render inside the if (ref.current === null) check, when writing it elsewhere in render is not?
Show answer
The write happens only once, while the value is still null, and every render produces the same resulting state. Nothing can observe a half-set ref, so the render stays predictable. Other writes change the ref on each render and make output depend on hidden data.