avatar
状态管理库Zustand

2026-04-28 | React状态管理

状态管理库Zustand

omnijk

Zustand:让React状态管理更简单、更高效

Zustand:让React状态管理更简单、更高效

在React项目开发中,状态管理一直是一个绕不开的话题。很多人提到状态管理,第一时间会想到Redux。Redux作为一个历史悠久的库,确实在功能性和中间件生态方面都有着不错的表现,但它复杂的配置和繁琐的代码书写让许多开发者望而却步。

优势

Zustand是一个轻量级、直观而强大的React状态管理库,它旨在提供一种比Redux和MobX等流行状态管理库更简单、更灵活的方式来管理React项目中的状态。Zustand的API清晰而简洁,学习起来不费力,且不需要繁琐的中间件和复杂的配置。此外,Zustand还天然支持TypeScript,增强了项目的健壮性。

对于追求简洁、高效且希望项目更为健壮的React开发者来说,Zustand无疑是一个值得探索和使用的新选项。在这个技术日新月异的时代,为自己的技术栈添加Zustand,或许能开启React状态管理的新篇章。

快速开始

安装:

npm install zustand

创建并使用一个简单的 store(计数器示例):

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

// 创建 store
const useStore = create((set) => ({
  count: 0,
  setCount: (num) => set({ count: num }),
  inc: () => set((state) => ({ count: state.count + 1 })),
}));

export default function Demo() {
  const { count, setCount, inc } = useStore();

  return (
    <div>
      {count}
      <input
        onChange={(event) => {
          setCount(Number(event.target.value));
        }}
      />
      <button onClick={inc}>Increase</button>
    </div>
  );
}

存储数组示例

如果需要在 store 中保存数组:

const useStore = create((set) => ({
  fruits: ["apple", "banana", "orange"],
  addFruits: (fruit) =>
    set((state) => ({
      fruits: [...state.fruits, fruit],
    })),
}));

访问与读取状态

可以使用 get() 在 store 内部读取其它状态:

const useStore = create((set, get) => ({
  votes: 0,
  action: () => {
    const userVotes = get().votes;
    // 根据 votes 进行后续操作
  },
}));

与 Redux 对比

Redux 需要定义 initial state、actions、reducers,样板代码较多;Zustand 更倾向于直接在 store 中定义状态与更新逻辑,使用更为直观:

// Redux 示例
import { createStore } from 'redux';

const initialState = { count: 0 };

function reducer(state = initialState, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + action.qty };
    default:
      return state;
  }
}

const store = createStore(reducer);
// Zustand 示例
import { create } from 'zustand';

const useCountStore = create((set) => ({
  count: 0,
  increment: (qty) => set((state) => ({ count: state.count + qty })),
}));

常见陷阱及解决方案

  • 组件未响应状态变化:在依赖状态进行副作用或条件渲染时,建议使用 useEffect 订阅并响应变化:
import React, { useEffect } from 'react';
import { useConfigStore } from './configStore';

const ThemedComponent = () => {
  const { theme } = useConfigStore();

  useEffect(() => {
    // 当 theme 变化时触发副作用
  }, [theme]);

  return (
    <div>
      <p>The current theme is: {theme}</p>
    </div>
  );
};

Zustand 是一款轻量、简单且灵活的状态管理库,适合希望减少样板代码并提升开发效率的项目。它与 React Hooks 深度集成,支持渐进式迁移与 TypeScript,在中小型项目或想要减轻状态管理复杂度的场景中尤其适用。

陕ICP备2026012647号

© 2026 omnijk. All rights reserved.

本网站内容仅供学习与交流使用,如有侵权或不当内容请联系删除。