:状态管理选型)
创作者Yardon |GitHubgithub.com/YardonYan |版本v1.0什么时候需要状态管理先泼一盆冷水大多数 React 应用不需要 Redux。这句话不是我说的是 Redux 的作者 Dan Abramov 本人说的。他在 2020 年就公开表示在他参与的大多数项目中Redux 已经不再是最好的选择。那么什么时候真的需要「状态管理库」当你的应用满足以下任意一个条件时超过 3 层嵌套的组件需要共享同一个状态多个不相关的页面需要访问同一份数据状态变更的逻辑非常复杂多个 action 之间有依赖关系需要时间旅行调试undo/redo其他情况useStateuseContext足够了。React 自带的方案回顾在介绍第三方库之前先把 React 自带的工具说清楚。Props Drilling属性穿透最基础的方式就是通过 props 一层层往下传App → Header → NavBar → Logo ↓ UserMenu → Avatar → Dropdown → Item如果 UserMenu 和 NavBar 都需要访问currentUser而currentUser定义在 App 组件里——你得把它一层层往下传。这在浅层嵌套时没问题但如果你的组件树有 5-6 层深每层都要过手一个跟它们毫无关系的 props这就成了「属性穿透地狱」。想象你在一栋公寓里每层都住着互不相识的邻居但暖气管道要穿过每一家的客厅。物业公司的员工中间组件被迫了解每家每户的暖气情况——尽管他只需要把暖气送到就行了。Context API内置的跨组件通信Context就是来解决这个问题的——让你在组件树的任意位置访问数据而不需要手动层层传递。Context API轻量级全局状态基本用法// ThemeContext.jsx import { createContext, useContext, useState } from #039;react#039;; const ThemeContext createContext(); export function ThemeProvider({ children }) { const [theme, setTheme] useState(#039;dark#039;); function toggleTheme() { setTheme(t t #039;dark#039; ? #039;light#039; : #039;dark#039;); } return ( lt;ThemeContext.Provider value{{ theme, toggleTheme }}gt; {children} lt;/ThemeContext.Providergt; ); } export function useTheme() { const context useContext(ThemeContext); if (!context) throw new Error(#039;useTheme 必须在 ThemeProvider 内使用#039;); return context; }// App.jsx import { ThemeProvider } from #039;./ThemeContext#039;; function App() { return ( lt;ThemeProvidergt; lt;Dashboard /gt; lt;/ThemeProvidergt; ); } // 任意子组件中 function SettingsPage() { const { theme, toggleTheme } useTheme(); return lt;button onClick{toggleTheme}gt;当前: {theme}lt;/buttongt;; }Context 的性能陷阱Context 最大的坑在于Provider 下的所有组件都会在 Context 值变化时重新渲染。// ❌ 每秒更新一次所有消费者都 re-render function App() { const [time, setTime] useState(Date.now()); useEffect(() gt; { const id setInterval(() gt; setTime(Date.now()), 1000); return () gt; clearInterval(id); }, []); return lt;ThemeContext.Provider value{{ time }}gt;...lt;/ThemeContext.Providergt;; } // ✅ 只暴露必要的状态 function App() { const [time, setTime] useState(Date.now()); const { theme } useThemeContext(); // 只订阅需要的 useEffect(() gt; { const id setInterval(() gt; setTime(Date.now()), 1000); return () gt; clearInterval(id); }, []); return lt;ThemeContext.Provider value{{ theme, time }}gt;...lt;/ThemeContext.Providergt;; }最佳实践按功能拆分成多个独立的 Context。// 主题一个 Context用户信息一个 Context购物车一个 Context // 每个 Context 只订阅它真正需要的数据 ThemeContext.Provider value{theme} UserContext.Provider value{user} CartContext.Provider value{cart} App / /CartContext.Provider /UserContext.Provider /ThemeContext.Provider这样只有购物车变了Header 里的主题切换按钮才不会无辜地重新渲染。Zustand极简主义的代表Zustand 是 2020 年后最火的状态管理库。它用起来非常简单——5 分钟就能上手。核心概念// store/useCartStore.js import { create } from #039;zustand#039;; const useCartStore create((set, get) gt; ({ items: [], total: 0, addItem: (product) gt; set((state) gt; ({ items: [...state.items, product], total: state.total product.price, })), removeItem: (id) gt; set((state) gt; { const item state.items.find(i gt; i.id id); return { items: state.items.filter(i gt; i.id ! id), total: state.total - (item?.price || 0), }; }), clearCart: () gt; set({ items: [], total: 0 }), // 直接读取 state不需要 hooks getItemCount: () gt; get().items.length, }));// 在组件中使用 function CartIcon() { const itemCount useCartStore(s gt; s.items.length); return lt;spangt; {itemCount}lt;/spangt;; } function CartPage() { const { items, total, removeItem, clearCart } useCartStore(); return ( lt;divgt; {items.map(item gt; lt;CartItem key{item.id} item{item} onRemove{removeItem} /gt;)} lt;pgt;总计: ¥{total}lt;/pgt; lt;button onClick{clearCart}gt;清空购物车lt;/buttongt; lt;/divgt; ); }为什么选择 Zustand特性ZustandRedux Toolkit代码量极简~50行一个store需要 action/reducer/store boilerplate学习曲线几乎为零中等概念多DevTools支持强大时间旅行等适用场景中小型应用大型复杂应用包大小~1KB~15KBRedux Toolkit复杂应用的选择Redux 曾经是 React 状态管理的代名词。2019 年 Redux Toolkit 的出现大幅降低了使用门槛但它的复杂性依然高于 Zustand。核心概念Slice// features/cart/cartSlice.jsimport{createSlice}from#039;reduxjs/toolkit#039;;constcartSlicecreateSlice({name:#039;cart#039;,initialState:{items:[],total:0},reducers:{addItem:(state,action)gt;{state.items.push(action.payload);state.totalaction.payload.price;},removeItem:(state,action)gt;{constidxstate.items.findIndex(igt;i.idaction.payload);if(idx!-1){state.total-state.items[idx].price;state.items.splice(idx,1);}},clearCart:(state)gt;{state.items[];state.total0;},},});exportconst{addItem,removeItem,clearCart}cartSlice.actions;exportdefaultcartSlice.reducer;// store/index.jsimport{configureStore}from#039;reduxjs/toolkit#039;;importcartReducer from#039;./features/cart/cartSlice#039;;exportconststoreconfigureStore({reducer:{cart:cartReducer,user:userReducer,// ...},});// 组件中使用 import { useSelector, useDispatch } from #039;react-redux#039;; import { addItem } from #039;./features/cart/cartSlice#039;; function ProductPage({ product }) { const dispatch useDispatch(); const isInCart useSelector(s gt; s.cart.items.some(i gt; i.id product.id) ); return ( lt;divgt; lt;h1gt;{product.name}lt;/h1gt; lt;button disabled{isInCart} onClick{() gt; dispatch(addItem(product))} gt; {isInCart ? #039;已在购物车#039; : #039;加入购物车#039;} lt;/buttongt; lt;/divgt; ); }Redux Toolkit 适合什么时候当你有多个开发者协作的大型项目需要严格的状态流转规范、时间旅行调试、批量操作日志时Redux 的约束反而是优点——它强制你用规范的方式做事不容易出现状态不知道从哪改的的情况。Jotai原子化状态管理Jotai 是一个相对小众但很有特色的方案。它的核心概念是原子Atom——最小的状态单元。// atoms.js import { atom } from #039;jotai#039;; // 基础原子 const userAtom atom(null); const notificationCountAtom atom(0); // 派生原子类似 useMemo const hasNotificationsAtom atom(get gt; get(notificationCountAtom) gt; 0); // 写原子 const addNotificationAtom atom( null, (get, set) gt; { const current get(notificationCountAtom); set(notificationCountAtom, current 1); } );// 组件中只订阅需要的原子 function NotificationBadge() { const count useAtom(notificationCountAtom)[0]; return count gt; 0 ? lt;spangt;{count}lt;/spangt; : null; } function NotificationButton() { const [, addNotification] useAtom(addNotificationAtom); return lt;button onClick{addNotification}gt;有新消息lt;/buttongt;; }Jotai 的优势是细粒度更新——只有真正用到某个原子值的组件才会重新渲染。它适合状态很多、更新很频繁的应用比如实时协作工具、数据可视化面板。选型决策树应用规模 ├── 小型几个页面状态简单 │ └── useState Context API ✅ 够了 │ ├── 中型10 页面多人协作 │ ├── 状态种类多、更新频繁 │ │ └── Zustand ✅ 推荐 │ │ │ └── 需要强规范、强调试能力 │ └── Redux Toolkit ✅ │ └── 大型复杂状态流转、undo/redo └── Redux Toolkit ✅ 或 Recoil我的推荐2026 年90% 的项目useStateContext或Zustand5% 的项目需要强规范Redux Toolkit5% 的项目状态极细Jotai本章小结工具适用场景代码量学习成本useState Context小型应用、简单全局状态少无Context API多 Context中型应用、分域全局状态中低Zustand中小型应用、需要灵活状态极少极低Redux Toolkit大型、复杂、多人协作多中Jotai细粒度状态、频繁更新少中状态管理的本质是数据的流向和共享。选什么工具不重要重要的是理解为什么需要它、它解决的是什么问题。下一章我们聊聊React Router——单页应用如何实现页面跳转和 URL 管理。创作者Yardon | 个人网站GlimmerAI.top 本章是「React 从入门到生产」系列的第 5 章。上一章自定义Hook | 下一章路由与导航 如果你觉得有帮助欢迎访问 GlimmerAI.top 查看我的更多作品。欢迎大家来观看