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

使用 Zustand 管理全局状态

集成轻量级状态管理库 Zustand,构建强大而灵活的全局状态解决方案

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

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

Meet Zustand for Global State

Welcome to Zustand! It's a small, fast, and scalable state management solution for React and Next.js applications.

Unlike some other libraries, Zustand is known for its simplicity and minimal boilerplate, making it easy to learn and use.

  • Simple: Uses a simple API based on React hooks.
  • Fast: Optimized for performance, avoiding unnecessary re-renders.
  • Scalable: Works well for small apps and large, complex projects.

Why Global State Matters

In larger applications, you often need to share data across many components that aren't directly connected (e.g., a user's login status or shopping cart items).

Without global state, you might find yourself 'prop drilling' – passing props down through many layers of components, which can be messy and hard to maintain.

Global state libraries like Zustand solve this by providing a central place to store and manage data accessible from any component.

Install Zustand in Your Project

Getting started with Zustand is straightforward. You just need to install it using your preferred package manager.

Open your terminal in your Next.js project directory and run one of the following commands:

  • npm: npm install zustand
  • yarn: yarn add zustand
  • pnpm: pnpm add zustand

Once installed, you're ready to create your first store!

Build Your First Zustand Store

A Zustand store is created using the create function. This function takes a callback that defines your initial state and any functions (actions) to modify that state.

The set argument in the callback is used to update the store's state. Let's define a basic counter store:

import { create } from 'zustand';
import React from 'react';

// Define your store
const useCounterStore = create((set) => ({
  count: 0, // Initial state
}));

// A dummy component to make it runnable
function StoreDefined() {
  return <p>Zustand store created!</p>;
}

export default function App() {
  return <StoreDefined />;
}

Access Store State in React

Now that we have a store, let's learn how to read its state within a React component. Zustand provides a hook (generated from your store) that you can call directly.

You can also use a 'selector' function to pick out just the specific pieces of state you need, avoiding unnecessary re-renders.

import { create } from 'zustand';
import React from 'react';

const useCounterStore = create((set) => ({
  count: 0,
}));

// This component reads the 'count' from the store
function CountDisplay() {
  const count = useCounterStore((state) => state.count);
  return (
    <div>
      <h3>Current Count:</h3>
      <p>{count}</p>
    </div>
  );
}

export default function App() {
  return <CountDisplay />;
}

Actions to Modify Store State

Stores are not just for reading data; they also define the actions that can modify the state. These actions are functions within your create call that use the set argument.

Let's add increment and decrement actions to our counter store and use them with buttons in a component:

import { create } from 'zustand';
import React from 'react';

const useCounterStore = create((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 })),
  decrement: () => set((state) => ({ count: state.count - 1 })),
}));

function CounterApp() {
  // Select both state and actions
  const { count, increment, decrement } = useCounterStore();
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  );
}

export default function App() {
  return <CounterApp />;
}

Optimize with State Selectors

If your store holds many values, a component that only uses a small part of the state might still re-render when other, unrelated parts of the state change.

Zustand's selector pattern helps prevent this. By providing a selector function to useStore, your component will only re-render if the *selected* part of the state changes.

import { create } from 'zustand';
import React from 'react';

const useUserProfileStore = create((set) => ({
  username: "Coddy",
  email: "coddy@example.com",
  loggedIn: true,
  updateUsername: (name) => set({ username: name }),
}));

// This component only cares about the username
function UsernameDisplay() {
  // Select only 'username' for efficient rendering
  const username = useUserProfileStore((state) => state.username);
  return (
    <div>
      <p>Hello, {username}!</p>
    </div>
  );
}

export default function App() {
  return <UsernameDisplay />;
}

Handle Asynchronous Updates

Zustand actions can easily handle asynchronous operations, such as fetching data from an API. You simply perform your async logic within the action and then call set when the data is ready.

This allows you to manage loading states or update data after network requests complete. Here's an example simulating a delayed update:

import { create } from 'zustand';
import React from 'react';

const useLoadingStore = create((set) => ({
  isLoading: false,
  message: "",
  fetchData: async () => {
    set({ isLoading: true, message: "Loading..." });
    // Simulate an API call
    await new Promise((resolve) => setTimeout(resolve, 1500));
    set({ isLoading: false, message: "Data Loaded!" });
  },
}));

function DataFetcher() {
  const { isLoading, message, fetchData } = useLoadingStore();
  return (
    <div>
      <p>{message}</p>
      <button onClick={fetchData} disabled={isLoading}>
        {isLoading ? "Fetching..." : "Fetch Data"}
      </button>
    </div>
  );
}

export default function App() {
  return <DataFetcher />;
}

Structure Your Zustand Stores

For larger Next.js applications, it's good practice to organize your Zustand stores. Instead of defining all stores in one file, create a dedicated file for each store (e.g., stores/userStore.js, stores/cartStore.js).

This keeps your codebase clean, modular, and easier to navigate. You can then import and use these store hooks wherever needed.

Test Your Zustand Skills

Consider the following Zustand store definition:

import { create } from 'zustand'; const useSettingsStore = create((set) => ({ theme: 'light', fontSize: 16, toggleTheme: () => set((state) => ({ theme: state.theme === 'light' ? 'dark' : 'light', })), setFontSize: (size) => set({ fontSize: size }), }));

If you call useSettingsStore((state) => state.theme) in a component, what will its initial value be?

Zustand: A Quick Review

Great job! You've successfully explored Zustand, a powerful and lightweight library for global state management in Next.js.

You learned how to:

  • Create a simple Zustand store.
  • Read state and dispatch actions in components.
  • Optimize performance using selectors.
  • Handle asynchronous updates.

Zustand's simplicity and flexibility make it an excellent choice for managing client-side global state in your applications. Keep practicing to master it!

常见问题解答

「使用 Zustand 管理全局状态」课时是免费的吗?

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

「使用 Zustand 管理全局状态」这节课中我会学到什么?

集成轻量级状态管理库 Zustand,构建强大而灵活的全局状态解决方案 你通过在浏览器中直接运行的动手代码来练习 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) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「使用 Zustand 管理全局状态」课时需要多长时间?

大多数 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)