0Pricing
Next.js 15 Fullstack (App Router + Server Actions) · Lesson

Persisting State to localStorage

Keep your client state across page reloads by persisting it to localStorage, handling hydration safely in Next.js, and using Zustand's persist middleware.

Persisting State to localStorage is a free Next.js 15 Fullstack (App Router + Server Actions) lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Next.js 15 Fullstack (App Router + Server Actions) learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Persist State?

By default, React state vanishes on reload. Persistence saves data like theme, cart contents, or draft text to the browser so it survives refreshes and revisits.

Meet localStorage

localStorage is a browser key-value store that keeps strings indefinitely. It is synchronous and scoped to the origin.

localStorage.setItem('theme', 'dark');
const theme = localStorage.getItem('theme');

Storing Objects

localStorage only holds strings, so serialize objects with JSON.stringify when saving and JSON.parse when reading.

localStorage.setItem('cart', JSON.stringify({ items: 3 }));
const cart = JSON.parse(localStorage.getItem('cart') || '{}');

The SSR Problem

Next.js renders components on the server first, where window and localStorage do not exist. Accessing them during render throws an error.

You must read localStorage only after the component mounts in the browser.

Reading Safely in useEffect

Read persisted state inside useEffect, which runs only on the client. Start with a safe default for the server render.

'use client';
const [theme, setTheme] = useState('light');
useEffect(() => {
  const saved = localStorage.getItem('theme');
  if (saved) setTheme(saved);
}, []);

Writing on Change

Sync state back to localStorage whenever it changes with another effect.

useEffect(() => {
  localStorage.setItem('theme', theme);
}, [theme]);

Avoiding Hydration Mismatch

If the server renders 'light' but the client immediately shows 'dark', React warns about a hydration mismatch. Render persisted UI only after a mounted flag is true.

const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
if (!mounted) return null;

Persisting Zustand Stores

Zustand ships a persist middleware that automatically saves your whole store to localStorage. Wrap your store creator with it.

import { create } from 'zustand';
import { persist } from 'zustand/middleware';

export const useCart = create(persist(
  (set) => ({ items: [], add: (i) => set((s) => ({ items: [...s.items, i] })) }),
  { name: 'cart-storage' }
));

Choosing What to Persist

You rarely want to persist everything. Use partialize to save only the fields that matter and keep transient UI state in memory.

persist(storeFn, {
  name: 'cart-storage',
  partialize: (s) => ({ items: s.items })
});

Versioning & Migration

When your state shape changes, bump version and provide a migrate function so old stored data upgrades instead of breaking the app.

persist(storeFn, {
  name: 'cart-storage',
  version: 2,
  migrate: (old, from) => ({ ...old, currency: 'USD' })
});

Best Practices

Persist state responsibly:

  • Serialize objects with JSON
  • Read only on the client to avoid SSR errors
  • Guard against hydration mismatches
  • Use Zustand persist with partialize and versioning

Quick Check

Test your persistence knowledge.

Recap

You learned to persist client state:

  • Store strings in localStorage, serializing objects with JSON
  • Read in useEffect and guard with a mounted flag
  • Use Zustand's persist middleware with partialize and versioned migrations

Your app now remembers user state across reloads.

Frequently asked questions

Is the “Persisting State to localStorage” lesson free?

Yes — the full text of “Persisting State to localStorage” is free to read here on the web, and the Next.js 15 Fullstack (App Router + Server Actions) course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Next.js 15 Fullstack (App Router + Server Actions) course, upgrade to CoddyKit PRO.

What will I learn in “Persisting State to localStorage”?

Keep your client state across page reloads by persisting it to localStorage, handling hydration safely in Next.js, and using Zustand's persist middleware. You practise Next.js 15 Fullstack (App Router + Server Actions) with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Next.js 15 Fullstack (App Router + Server Actions)?

No prior experience is required. Next.js 15 Fullstack (App Router + Server Actions) on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Persisting State to localStorage” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Next.js 15 Fullstack (App Router + Server Actions) lesson?

Yes. Every Next.js 15 Fullstack (App Router + Server Actions) lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. React Context API
  2. Global State with Zustand
  3. Managing Server State
  4. Persisting State to localStorage
← Back to Next.js 15 Fullstack (App Router + Server Actions)