Course contentsShow
← React
Lesson 774 of 2,39620. useReducerFree lesson

When Lazy Initialization Matters

Identifying scenarios where lazy init helps: reading localStorage, parsing large data, or complex derived calculations.

When Lazy Initialization Matters

What you'll learn: How to recognize the scenarios where lazy initialization with useReducer provides real performance benefits instead of just adding complexity.

The Real-World Triggers

Not every initial state calculation needs lazy initialization. You should reach for the init function parameter when your initial state involves one of these three expensive operations:

1. Reading from localStorage

Every localStorage.getItem() call is synchronous and blocks the main thread. If you're reading multiple keys or large stored objects on every render, you're wasting cycles:

// Without lazy init: reads localStorage on EVERY render
const [state, dispatch] = useReducer(reducer, JSON.parse(localStorage.getItem('data')));

// With lazy init: reads localStorage ONCE
const [state, dispatch] = useReducer(reducer, null, initFromLocalStorage);

2. Parsing Large Data Structures

Transforming a large API response, flattening nested arrays, or building lookup maps can be computationally expensive. If this happens inline, React runs it every time your component function executes during re-renders.

3. Complex Derived Calculations

Computing initial values based on multiple props with mathematical operations, filters, or sorts adds up. When these calculations only matter once (at mount), lazy initialization defers them until needed.

The Mental Model

Think of lazy initialization like a restaurant's mise en place—you don't prep ingredients for every customer who might order. You prep once when the kitchen opens. Similarly, init runs once when the reducer is created, not on every component render.

Key Takeaway: Use lazy initialization when your initial state requires reading from storage, processing large datasets, or expensive calculations—operations you only want to run once at mount, not on every render.