Persistindo o Estado no localStorage
Mantenha o estado do cliente após recarregar as páginas persistindo-o no localStorage, tratando a hidratação com segurança no Next.js e usando o middleware persist do Zustand.
Persistindo o Estado no localStorage é uma aula grátis de Next.js 15 Fullstack (App Router + Server Actions) no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Next.js 15 Fullstack (App Router + Server Actions), e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Next.js 15 Fullstack (App Router + Server Actions) inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em 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.
Aprenda TypeScript com um tutor de IA — grátis
Escreva e execute código real no seu navegador, obtenha ajuda instantânea de um tutor de IA 24/7 e continue de onde parou na web ou no app.
- Cursos
- 22
- Aulas
- 88
Perguntas Frequentes
A aula “Persistindo o Estado no localStorage” é grátis?
Sim — o texto completo de “Persistindo o Estado no localStorage” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Next.js 15 Fullstack (App Router + Server Actions), atualize para CoddyKit PRO. O curso de Next.js 15 Fullstack (App Router + Server Actions) inclui 4 aulas no total.
O que vou aprender em “Persistindo o Estado no localStorage”?
Mantenha o estado do cliente após recarregar as páginas persistindo-o no localStorage, tratando a hidratação com segurança no Next.js e usando o middleware persist do Zustand. Você pratica Next.js 15 Fullstack (App Router + Server Actions) com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Next.js 15 Fullstack (App Router + Server Actions)?
Nenhuma experiência prévia é necessária. Next.js 15 Fullstack (App Router + Server Actions) no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Persistindo o Estado no localStorage”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Next.js 15 Fullstack (App Router + Server Actions)?
Sim. Cada aula de Next.js 15 Fullstack (App Router + Server Actions) inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- API Context do React
- Estado global com Zustand
- Gerenciando o estado do servidor
- Persistindo o Estado no localStorage