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

Utrwalanie stanu w localStorage

Zachowaj stan klienta po przeładowaniu strony, zapisując go w localStorage, bezpiecznie obsługując hydration w Next.js i używając middleware persist biblioteki Zustand.

Utrwalanie stanu w localStorage to bezpłatna lekcja Next.js 15 Fullstack (App Router + Server Actions) na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Next.js 15 Fullstack (App Router + Server Actions), a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Next.js 15 Fullstack (App Router + Server Actions) zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

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.

Często zadawane pytania

Czy lekcja „Utrwalanie stanu w localStorage” jest bezpłatna?

Tak — pełny tekst „Utrwalanie stanu w localStorage” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Next.js 15 Fullstack (App Router + Server Actions), przejdź na CoddyKit PRO. Kurs Next.js 15 Fullstack (App Router + Server Actions) zawiera 4 lekcji w sumie.

Co nauczysz się w „Utrwalanie stanu w localStorage”?

Zachowaj stan klienta po przeładowaniu strony, zapisując go w localStorage, bezpiecznie obsługując hydration w Next.js i używając middleware persist biblioteki Zustand. Ćwiczysz Next.js 15 Fullstack (App Router + Server Actions) z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Next.js 15 Fullstack (App Router + Server Actions)?

Nie wymagamy żadnego doświadczenia. Next.js 15 Fullstack (App Router + Server Actions) w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.

Ile czasu zajmuje lekcja „Utrwalanie stanu w localStorage”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Next.js 15 Fullstack (App Router + Server Actions)?

Tak. Każda lekcja Next.js 15 Fullstack (App Router + Server Actions) zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. React Context API
  2. Stan globalny z Zustand
  3. Zarządzanie stanem serwera
  4. Utrwalanie stanu w localStorage
← Powrót do Next.js 15 Fullstack (App Router + Server Actions)