Part 10 / Topic 5 of 8
Lazy initialization: useReducer's third argument
useReducer's full signature is useReducer(reducer, initialArg, init). With a third argument, React computes the real initial state by calling init(initialArg) - and it calls that exactly once, on this component's first render, never again for any later re-render. examples/04_lazy_init.jsx's CartWithLazyInit uses this to restore a saved cart from localStorage without re-reading it on every render:
// examples/04_lazy_init.jsx
function loadInitialCart(storageKey) {
loadCallCounts[storageKey] = (loadCallCounts[storageKey] ?? 0) + 1;
const stored = window.localStorage.getItem(storageKey);
return stored !== null ? JSON.parse(stored) : { items: [] };
}
export function CartWithLazyInit({ storageKey }) {
const [cart, dispatch] = useReducer(cartReducer, storageKey, loadInitialCart);
// ...
}
Pre-seeding localStorage and rendering CartWithLazyInit really restores the saved cart; clicking "Add Butter Naan" twice afterward really moves the render count from 1 to 3 while loadCallCounts for that key really stays at 1 the entire time (examples/04_lazy_init.test.jsx) - the render count proves rerenders really happened, and the call count proves the (potentially expensive) restore logic was not repeated for any of them. Without the third argument, useReducer(cartReducer, loadInitialCart(storageKey)) would call loadInitialCart fresh on every single render just to throw the result away whenever it wasn't the first one - the exact same waste Part 7's lazy useState(() => ...) initializer exists to avoid, for the identical reason.
Done here? The practice set for Part 10 — including the solutions — is on the part page.