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

将状态持久化到 localStorage

将客户端状态持久化到 localStorage,使其在页面重新加载后保留;同时在 Next.js 中安全处理水合,并使用 Zustand 的 persist 中间件。

将状态持久化到 localStorage 是 CoddyKit 上的免费 Next.js 15 Fullstack (App Router + Server Actions) 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Next.js 15 Fullstack (App Router + Server Actions) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Next.js 15 Fullstack (App Router + Server Actions) 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

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.

常见问题解答

「将状态持久化到 localStorage」课时是免费的吗?

是的 — 「将状态持久化到 localStorage」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Next.js 15 Fullstack (App Router + Server Actions) 课程的其余内容,请升级到 CoddyKit PRO。 Next.js 15 Fullstack (App Router + Server Actions) 课程共包含 4 节课。

「将状态持久化到 localStorage」这节课中我会学到什么?

将客户端状态持久化到 localStorage,使其在页面重新加载后保留;同时在 Next.js 中安全处理水合,并使用 Zustand 的 persist 中间件。 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack (App Router + Server Actions),全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Next.js 15 Fullstack (App Router + Server Actions) 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Next.js 15 Fullstack (App Router + Server Actions) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「将状态持久化到 localStorage」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Next.js 15 Fullstack (App Router + Server Actions) 课中编写并运行代码吗?

能。每节 Next.js 15 Fullstack (App Router + Server Actions) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. React Context API
  2. 使用 Zustand 管理全局状态
  3. 管理服务器状态
  4. 将状态持久化到 localStorage
← 返回 Next.js 15 Fullstack (App Router + Server Actions)