Next.js 15 Fullstack (App Router + Server Actions) · Lektion

Zustand in localStorage speichern

Bewahren Sie Ihren Client-Zustand über Seitenneuladungen hinweg, indem Sie ihn in localStorage speichern, die Hydration in Next.js sicher behandeln und die persist-Middleware von Zustand verwenden

Lektion 4 von 413 Schritte

Zustand in localStorage speichern ist eine kostenlose Next.js 15 Fullstack (App Router + Server Actions)-Lektion auf CoddyKit. Dies ist Lektion 4 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Next.js 15 Fullstack (App Router + Server Actions)-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Next.js 15 Fullstack (App Router + Server Actions)-Kurs umfasst insgesamt 4 Lektionen.

Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.

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.

Kostenlos starten

Lerne TypeScript mit einem KI-Tutor — kostenlos

Schreibe und führe echten Code in deinem Browser aus, bekomme sofortige Hilfe von einem 24/7 KI-Tutor und setze dein Lernen im Web oder in der App fort.

Kurse
22
Lektionen
88

Häufig gestellte Fragen

Ist die Lektion „Zustand in localStorage speichern“ kostenlos?

Ja — der vollständige Text von „Zustand in localStorage speichern“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Next.js 15 Fullstack (App Router + Server Actions)-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Next.js 15 Fullstack (App Router + Server Actions)-Kurs umfasst insgesamt 4 Lektionen.

Was lerne ich in „Zustand in localStorage speichern“?

Bewahren Sie Ihren Client-Zustand über Seitenneuladungen hinweg, indem Sie ihn in localStorage speichern, die Hydration in Next.js sicher behandeln und die persist-Middleware von Zustand verwenden Du übst Next.js 15 Fullstack (App Router + Server Actions) mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.

Brauche ich Erfahrung, um Next.js 15 Fullstack (App Router + Server Actions) zu starten?

Keine Vorkenntnisse erforderlich. Next.js 15 Fullstack (App Router + Server Actions) auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 4 von 4.

Wie lange dauert die Lektion „Zustand in localStorage speichern“?

Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.

Kann ich in dieser Next.js 15 Fullstack (App Router + Server Actions)-Lektion Code schreiben und ausführen?

Ja. Jede Next.js 15 Fullstack (App Router + Server Actions)-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.

Alle Lektionen in diesem Kurs

  1. React Context API
  2. Globaler Zustand mit Zustand
  3. Serverzustand verwalten
  4. Zustand in localStorage speichern
← Zurück zu Next.js 15 Fullstack (App Router + Server Actions)