Reading from localStorage at Initialization
You'll learn how to safely read persisted state from localStorage when your component first mounts, using lazy initialization to avoid performance pitfalls.
The Problem
Sometimes you want your state to survive page refreshes. The browser's localStorage API lets you save data permanently, but when you read from it matters. If you do this:
const [count, setCount] = useState(localStorage.getItem('count') || 0);
You're calling localStorage.getItem() on every single render, even though the initial value only matters the very first time. That's wasteful.
The Solution: Lazy Initialization with localStorage
Remember lazy initial state from the previous lesson? It's perfect here. Pass a function to useState, and React will only call it once during initialization:
const [count, setCount] = useState(() => {
const saved = localStorage.getItem('count');
return saved !== null ? JSON.parse(saved) : 0;
});
Now the localStorage read happens only once when the component mounts. On subsequent re-renders, React skips that function entirely.
Why JSON.parse?
localStorage stores everything as strings. JSON.parse() converts "42" back to the number 42. If there's nothing saved (null), we fall back to our default value.
The Analogy
Think of it like checking your mailbox when you get home. You only check once (initialization), not every time you walk past the door (re-render).
Key Takeaway: Use lazy initialization (useState(() => ...)) when reading from localStorage to ensure the potentially expensive read only happens once at mount, not on every render.