🐻 前端状态管理不再头秃?试试 Zustand,这只“状态之熊”!

209 阅读3分钟

“当你还在 useContext + useReducer 中绕圈时,Zustand 已经优雅地把状态握在了熊掌之中。”——一个被 Redux 搞到脱发的前端

一、前言:我为什么开始用 Zustand?

作为一名 React 开发小白/进阶者,我曾经也对状态管理一头雾水:

  • useState 能用,但组件间一多,props 传疯了;
  • useReducer 配合 Context 用上后,代码看起来像 Redux 微缩版;
  • 真·Redux 配起来更猛:action、reducer、middleware、store,一套流程猛如虎,debug 却如走迷宫;
  • Recoil / Jotai / MobX / Redux Toolkit 一一试过,总感觉有点“大材小用”。

直到我遇到了它——Zustand,一只简约不失灵性的状态管理“熊”。


二、Zustand 是啥?一分钟带你入门

Zustand 是由 PMNDRE 团队开发的一个 轻量级、无模板、hooks 风格的状态管理库,支持:

✅ 极简 API
✅ React 友好(不用 Provider)
✅ 支持中间件、异步、选择器(selector)等进阶用法
✅ 性能优秀,按需渲染

Zustand 在德语中意为“状态”,也象声“熊掌”的感觉,所以 logo 是只熊🐻。


三、来点实战:三步学会 Zustand

第 1 步:安装 Zustand

npm install zustand
# or
yarn add zustand

第 2 步:创建状态仓库(store)

// src/store/useBearStore.ts
import { create } from 'zustand'

interface BearState {
  bears: number
  increase: () => void
}

export const useBearStore = create<BearState>((set) => ({
  bears: 0,
  increase: () => set((state) => ({ bears: state.bears + 1 })),
}))

是不是已经被简洁惊艳到?没有 action type,没有 dispatch,没有 reducer

第 3 步:在组件中使用

// App.tsx
import React from 'react'
import { useBearStore } from './store/useBearStore'

export default function App() {
  const bears = useBearStore((state) => state.bears)
  const increase = useBearStore((state) => state.increase)

  return (
    <div>
      <h1>🐻 熊的数量:{bears}</h1>
      <button onClick={increase}>增加一只熊</button>
    </div>
  )
}

组件只会因为自己订阅的 state 更新,避免全量刷新,提高性能!


四、Zustand 的强大特性

1. 无 Provider 设计

不用在顶层包一圈 <StoreProvider>,简直是 React 小白福音。

2. 局部订阅,性能优化

const bears = useBearStore(state => state.bears)

你订阅啥,就只会因为它变动而重渲染。

3. 异步请求管理

const useUserStore = create((set) => ({
  user: null,
  fetchUser: async () => {
    const res = await fetch('/api/user')
    const user = await res.json()
    set({ user })
  },
}))

4. 中间件支持(如 persist, devtools)

import { create } from 'zustand'
import { persist, devtools } from 'zustand/middleware'

const useStore = create(
  devtools(
    persist(
      (set) => ({
        count: 0,
        inc: () => set((state) => ({ count: state.count + 1 })),
      }),
      { name: 'counter-storage' }
    )
  )
)

五、Zustand vs Redux vs Recoil?

对比维度Zustand 🐻ReduxRecoil
代码简洁度极简,仅用 Hooks繁琐,模板多适中,概念多
学习曲线
异步支持内置支持需要 middleware支持
Provider 需求❌ 无需✅ 必须✅ 必须
渲染性能✅ 局部订阅❌ 全量✅ 原子级订阅
开发者工具✅ DevTools 插件✅ 官方支持✅ 官方支持

总结一句话:Zustand 更像是“Hooks 化”的 Redux,但比 Redux 更轻盈、更自然。


六、适合哪些场景?

✅ 中小型应用,全局状态少
✅ 配合 React Query 管理 UI 状态
✅ 替代复杂 Context + Reducer 的方案
✅ 初学者上手状态管理

⚠️ 不适合:
🚫 需要大量状态分片依赖、高度结构化的大型项目(这时候 Redux Toolkit 更合适)


七、总结一下这只“熊”的优点 🐾

  1. 轻量级:不到 1kb,告别笨重 Redux。
  2. 无需 Provider:组件即用即取。
  3. 简洁 API:Hooks 写法,优雅自然。
  4. 中间件丰富:支持持久化、本地存储、DevTools 等。
  5. 按需渲染:性能好,更新只影响订阅组件。

八、最后一口“熊语”🐻:Zustand 适合你吗?

如果你是:

  • 刚入门 React 状态管理,不想一上来就跪在 Redux 面前;
  • 想写出 高性能、低心智负担 的组件逻辑;
  • 喜欢 Hooks 这一套“即插即用”的风格;

那就别犹豫,让这只 Zustand 之熊为你保驾护航吧!


🧠 附加阅读推荐:


如果你喜欢这篇文章,不妨点个赞 👍 + 收藏 ⭐,让更多人告别“状态焦虑”!

还想看哪种 React 技术或库?评论区见 🗣️