Course contentsShow
← React
Lesson 390 of 2,39611. useState Patterns and PitfallsFree lesson

Reading from localStorage Lazily

Apply lazy initialization to avoid JSON parsing on every render when loading persisted state from localStorage.

Reading from localStorage Lazily

What you'll learn: How to avoid parsing JSON from localStorage on every single render by using lazy initialization.


The Problem with Direct localStorage Reads

When you initialize state by reading from localStorage, it looks tempting to do this:

const [theme, setTheme] = useState(
  JSON.parse(localStorage.getItem('theme')) || 'light'
);

But remember: this code runs on every render. Even though useState only uses the initial value once, JavaScript still has to:

  1. Call localStorage.getItem()
  2. Parse the JSON string
  3. Evaluate the || fallback

...every single time your component re-renders. If the user clicks a button, types in a field, or anything else triggers a re-render, that localStorage read and parse happens again (and is thrown away).

The Solution: Lazy Initialization

Wrap your localStorage logic in a function:

const [theme, setTheme] = useState(() => {
  const saved = localStorage.getItem('theme');
  return saved ? JSON.parse(saved) : 'light';
});

Now the localStorage read and JSON parsing only happen once, during the initial render. On subsequent re-renders, React sees the function and knows "I already have state, skip this."

The Performance Win

Analogy: It's like checking your mailbox. Without lazy initialization, you walk to the mailbox every time you enter your house—even though you already brought in today's mail. With lazy initialization, you only check once per day.

For simple values this doesn't matter much, but for complex objects or slow storage operations, the savings add up.

Key Takeaway: Always use the function form useState(() => JSON.parse(localStorage.getItem(...))) when reading persisted state—it runs the expensive operation only once instead of on every render.