Persistenza dello stato in localStorage
Mantenga lo stato client tra i ricaricamenti della pagina salvandolo in localStorage, gestendo l’hydration in sicurezza in Next.js e usando il middleware persist di Zustand.
Persistenza dello stato in localStorage è una lezione Next.js 15 Fullstack (App Router + Server Actions) gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Next.js 15 Fullstack (App Router + Server Actions), e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Next.js 15 Fullstack (App Router + Server Actions) include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
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
useEffectand guard with amountedflag - Use Zustand's
persistmiddleware withpartializeand versioned migrations
Your app now remembers user state across reloads.
Domande Frequenti
La lezione «Persistenza dello stato in localStorage» è gratuita?
Sì — il testo completo di «Persistenza dello stato in localStorage» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Next.js 15 Fullstack (App Router + Server Actions), passa a CoddyKit PRO. Il corso Next.js 15 Fullstack (App Router + Server Actions) include 4 lezioni in totale.
Cosa imparerò in «Persistenza dello stato in localStorage»?
Mantenga lo stato client tra i ricaricamenti della pagina salvandolo in localStorage, gestendo l’hydration in sicurezza in Next.js e usando il middleware persist di Zustand. Eserciti Next.js 15 Fullstack (App Router + Server Actions) con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Next.js 15 Fullstack (App Router + Server Actions)?
Non è richiesta alcuna esperienza precedente. Next.js 15 Fullstack (App Router + Server Actions) su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Persistenza dello stato in localStorage»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Next.js 15 Fullstack (App Router + Server Actions)?
Sì. Ogni lezione Next.js 15 Fullstack (App Router + Server Actions) include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- React Context API
- Stato globale con Zustand
- Gestire lo stato del server
- Persistenza dello stato in localStorage