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
localStorageorsessionStorage. - Creating large arrays or maps.
- Parsing the URL or decoding a token.
- Creating class instances such as a
Mapof caches.
Details
- Pass the function itself:
useState(createTodos), notuseState(createTodos()). - The initializer must be pure. In Strict Mode development React calls it twice to check.
- It receives no arguments.
useReducerhas 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";23function loadSettings() {4 console.log("parsing settings"); // with lazy init: logged once, not on every render5 try {6 return JSON.parse(localStorage.getItem("settings") ?? "") as { fontSize: number; compact: boolean };7 } catch {8 return { fontSize: 16, compact: false };9 }10}1112export function Settings() {13 // Wrong: loadSettings() runs on every render14 // const [settings, setSettings] = useState(loadSettings());1516 // Right: runs only on the first render17 const [settings, setSettings] = useState(loadSettings);1819 return (20 <label>21 <input22 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.