Next.js 15 Fullstack Web Apps · Урок

Состояние на стороне клиента с Zustand/Jotai

Реализуйте лёгкое и производительное глобальное управление состоянием на стороне клиента с помощью Zustand или Jotai.

Урок 2 из 411 шагов

«Состояние на стороне клиента с Zustand/Jotai» — бесплатный урок Next.js 15 Fullstack Web Apps на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Next.js 15 Fullstack Web Apps, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Next.js 15 Fullstack Web Apps содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Global State: Beyond Local

In React, you've learned about local state with useState, which is great for data used only within a single component.

But what if data needs to be shared across many components, or deeply nested components, without 'prop drilling' (passing props down through many layers)? This is where client-side global state management comes in.

Global state allows any component to access or update shared data directly, simplifying complex data flows and making your application more maintainable.

Meet Zustand: Simple State

Zustand is a small, fast, and scalable state management solution for React. Its API is simple and hooks-based, making it very intuitive to learn and use.

  • Minimalistic: Less boilerplate code.
  • Fast: Optimized for performance.
  • Flexible: Works with any React component.
  • Hooks-based: Feels natural to React developers.

Get Started with Zustand

Before we dive into creating stores, you'll need to install Zustand in your Next.js project. It's a simple npm or yarn command.

Open your terminal in the project root and run:

npm install zustand

Or if you prefer Yarn:

yarn add zustand

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

Crafting a Zustand Store

A Zustand store is created using the create function. This function takes a callback that defines your initial state and actions.

Think of a store as a central hub for specific pieces of global data. Let's create a basic counter store:

import { create } from 'zustand';

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

// This store can be imported and used in your React components.
// It's not runnable on its own, but defines the global state structure.

Store State & Actions

Beyond just holding state, a store also contains actions – functions that modify the state. The set function provided by Zustand allows you to update the store's state.

Here's how we add increment and decrement actions to our counter store:

import { create } from 'zustand';

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

// This store now has both state (count) and actions (increment, decrement).

Connect Components to Store

To use the global state in your React components, you simply import the store hook (e.g., useCounterStore) and call it. You can select specific pieces of state or actions.

Let's create a component that displays the current count from our store:

import { create } from 'zustand';

// Define your store (as in previous scenes)
const useCounterStore = create((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 })),
  decrement: () => set((state) => ({ count: state.count - 1 })),
}));

// A React component that uses the store
export default function CounterDisplay() {
  // Select the 'count' state from the store
  const count = useCounterStore((state) => state.count);

  return (
    <div>
      <p>Current Count: {count}</p>
    </div>
  );
}

// This component can be rendered in a Next.js page or another component.

Interactive Counter Example

Now let's make our counter interactive! We'll add buttons that call the increment and decrement actions defined in our store.

This shows how components can both read from and write to the global state, keeping everything synchronized.

import { create } from 'zustand';

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

// A React component that uses the store and its actions
export default function InteractiveCounter() {
  // Select both state and actions
  const { count, increment, decrement } = useCounterStore();

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={decrement}>Decrement</button>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

// This component is fully runnable and demonstrates Zustand in action.

Efficient State Selection

By default, if any part of the store's state changes, components that use the store might re-render. To optimize this, you can use selectors.

A selector is a function you pass to useStore that picks only the specific data your component needs. If only that selected data changes, the component re-renders.

import { create } from 'zustand';

// A more complex store with multiple states
const useSettingsStore = create((set) => ({
  theme: 'dark',
  fontSize: 16,
  toggleTheme: () => set((state) => ({ theme: state.theme === 'dark' ? 'light' : 'dark' })),
  setFontSize: (size) => set({ fontSize: size }),
}));

// Component only cares about 'theme'
export default function ThemeDisplay() {
  // Using a selector to only subscribe to 'theme'
  const theme = useSettingsStore((state) => state.theme);

  return (
    <p>Current Theme: <b>{theme}</b></p>
  );
}

// If fontSize changes, ThemeDisplay will NOT re-render because it only selects 'theme'.

Zustand Best Practices

To keep your Zustand stores clean and efficient:

  • Immutability: Always update state immutably. Don't directly modify objects or arrays in state; create new ones.
  • Separate Concerns: Keep related state and actions in the same store. Create multiple stores for different domains (e.g., useUserStore, useCartStore).
  • Selectors: Use selectors to prevent unnecessary re-renders in components.
  • Middleware: For advanced features like persistence or logging, explore Zustand's middleware options.

Zustand Knowledge Check

Zustand offers a flexible and lightweight approach to global state management. Based on what you've learned, choose the correct statements about its benefits and characteristics.

Zustand: A Quick Recap

Congratulations! You've learned the fundamentals of client-side global state management with Zustand.

  • We explored why global state is essential for complex apps.
  • You saw how to define a Zustand store with state and actions using create.
  • We learned to connect React components to the store and interact with its state and actions.
  • Finally, we discussed how selectors can optimize component re-renders.

Zustand empowers you to manage shared data efficiently, making your Next.js applications more scalable and easier to maintain.

Можно начать бесплатно

Изучай TypeScript с ИИ-репетитором — бесплатно

Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.

Курсы
12
Уроки
48

Часто задаваемые вопросы

Урок «Состояние на стороне клиента с Zustand/Jotai» бесплатный?

Да — полный текст урока «Состояние на стороне клиента с Zustand/Jotai» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Next.js 15 Fullstack Web Apps, подпишись на CoddyKit PRO. Курс Next.js 15 Fullstack Web Apps содержит 4 уроков всего.

Чему я научусь в уроке «Состояние на стороне клиента с Zustand/Jotai»?

Реализуйте лёгкое и производительное глобальное управление состоянием на стороне клиента с помощью Zustand или Jotai. Ты практикуешь Next.js 15 Fullstack Web Apps с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Next.js 15 Fullstack Web Apps?

Предыдущий опыт не требуется. Next.js 15 Fullstack Web Apps на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «Состояние на стороне клиента с Zustand/Jotai»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Next.js 15 Fullstack Web Apps?

Да. Каждый урок Next.js 15 Fullstack Web Apps включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. React Query для состояния сервера
  2. Состояние на стороне клиента с Zustand/Jotai
  3. Стратегии кэширования на стороне сервера
  4. Оптимистичные обновления и аннулирование кэша
← Назад к Next.js 15 Fullstack Web Apps