Persistencia del estado en localStorage
Conserve el estado del cliente entre recargas de página guardándolo en localStorage, gestionando la hidratación de forma segura en Next.js y utilizando el middleware persist de Zustand.
Persistencia del estado en localStorage es una lección gratuita de Next.js 15 Fullstack (App Router + Server Actions) en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Next.js 15 Fullstack (App Router + Server Actions), y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Next.js 15 Fullstack (App Router + Server Actions) incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
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.
Aprende TypeScript con un tutor de IA — gratis
Escribe y ejecuta código real en tu navegador, obtén ayuda instantánea de un tutor de IA disponible 24/7 y continúa donde lo dejaste en la web o en la aplicación.
- Cursos
- 22
- Lecciones
- 88
Preguntas frecuentes
¿La lección «Persistencia del estado en localStorage» es gratis?
Sí — el texto completo de «Persistencia del estado en localStorage» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Next.js 15 Fullstack (App Router + Server Actions), actualiza a CoddyKit PRO. El curso de Next.js 15 Fullstack (App Router + Server Actions) incluye 4 lecciones en total.
¿Qué aprenderé en «Persistencia del estado en localStorage»?
Conserve el estado del cliente entre recargas de página guardándolo en localStorage, gestionando la hidratación de forma segura en Next.js y utilizando el middleware persist de Zustand. Practicas Next.js 15 Fullstack (App Router + Server Actions) con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Next.js 15 Fullstack (App Router + Server Actions)?
No se requiere experiencia previa. Next.js 15 Fullstack (App Router + Server Actions) en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Persistencia del estado en localStorage»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Next.js 15 Fullstack (App Router + Server Actions)?
Sí. Cada lección de Next.js 15 Fullstack (App Router + Server Actions) incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- React Context API
- Estado global con Zustand
- Gestión del estado del servidor
- Persistencia del estado en localStorage