ReactEasy

What is lazy initialization in useState?

Lazy initialization means passing a function to useState instead of a value: useState(() => computeInitial()). React calls that function only on the first render and ignores it afterwards, so expensive setup work (parsing localStorage, building large structures) does not run on every render.

Why it matters

useState(expensive()) calls expensive() on every render, even though React only uses the result the first time. The arrow-function form runs it once.

Good candidates

  • Reading and parsing localStorage or sessionStorage.
  • Creating large arrays or maps.
  • Parsing the URL or decoding a token.
  • Creating class instances such as a Map of caches.

Details

  • Pass the function itself: useState(createTodos), not useState(createTodos()).
  • The initializer must be pure. In Strict Mode development React calls it twice to check.
  • It receives no arguments.
  • useReducer has the same idea through its third argument: useReducer(reducer, arg, init).
  • For values that need to be created once but never change and do not need re-renders, a lazily initialized useRef (if (ref.current === null) ref.current = create()) is an alternative.

Not a fix for

Values that depend on props changing later. The initializer only runs on mount; use a key to remount, or derive during render.

Code example

tsx
1import { useState } from "react";
2
3function loadSettings() {
4 console.log("parsing settings"); // with lazy init: logged once, not on every render
5 try {
6 return JSON.parse(localStorage.getItem("settings") ?? "") as { fontSize: number; compact: boolean };
7 } catch {
8 return { fontSize: 16, compact: false };
9 }
10}
11
12export function Settings() {
13 // Wrong: loadSettings() runs on every render
14 // const [settings, setSettings] = useState(loadSettings());
15
16 // Right: runs only on the first render
17 const [settings, setSettings] = useState(loadSettings);
18
19 return (
20 <label>
21 <input
22 type="checkbox"
23 checked={settings.compact}
24 onChange={(e) => {
25 const next = { ...settings, compact: e.target.checked };
26 setSettings(next);
27 localStorage.setItem("settings", JSON.stringify(next));
28 }}
29 />
30 Compact mode (font {settings.fontSize}px)
31 </label>
32 );
33}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app