Zustand:轻量级 React 状态管理新选择

Sarah Wong | 2026-09-01T08:57:09 | JavaScript, Frontend

对比 Redux/Zustand/Jotai,深入 Zustand 的 create/subscribe 机制、中间件系统、persist 持久化以及与 React Server Components 的兼容性。

# Zustand:轻量级 React 状态管理新选择 ## 为什么选择 Zustand Zustand 没有 Provider 包裹、没有 action type 字符串、没有 reducer boilerplate,API 极其简洁。 ```typescript import { create } from 'zustand' interface AuthStore { user: User | null token: string | null login: (credentials: LoginDTO) => Promise logout: () => void } const useAuthStore = create((set, get) => ({ user: null, token: null, login: async (credentials) => { const resp = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(credentials) }) const data = await resp.json() set({ user: data.user, token: data.token }) }, logout: () => set({ user: null, token: null }) })) ``` ## 组件中使用 ```tsx function UserProfile() { // 只订阅需要的字段,减少不必要的重渲染 const user = useAuthStore((state) => state.user) const logout = useAuthStore((state) => state.logout) if (!user) return return ( Welcome, {user.name} Logout ) } ``` ## 中间件:persist + devtools ```typescript import { create } from 'zustand' import { persist, devtools } from 'zustand/middleware' const useCartStore = create( devtools( persist( (set, get) => ({ items: [], addItem: (product) => set((state) => ({ items: [...state.items, { ...product, quantity: 1 }] })), removeItem: (id) => set((state) => ({ items: state.items.filter((item) => item.id !== id) })), total: () => get().items.reduce( (sum, item) => sum + item.price * item.quantity, 0 ) }), { name: 'cart-storage', partialize: (state) => ({ items: state.items }) } ), { name: 'CartStore' } ) ) ``` ## 组件外访问 Store ```typescript // 在非 React 环境中访问 store const currentUser = useAuthStore.getState().user useAuthStore.subscribe((state) => { console.log('State changed:', state) }) ``` Zustand 的 bundle size 仅约 1KB(gzip),性能优异。推荐在中小型项目中作为 Redux 的替代品,大型项目如需严格的 action 追踪仍可考虑 Redux Toolkit。

← Back to Blog