文章预览
为什么选择 Zustand? Zustand 是一个为 React 打造的现代化状态管理库,它以其简洁的 API 和强大的功能正在改变前端开发的方式。相比 Redux 繁琐的样板代码(action types、dispatch、Provider等),Zustand 提供了更加优雅且直观的解决方案。 核心特性 1. 基于 Hook 的简洁API import { create } from 'zustand' // 创建 store const useStore = create( ( set ) => ({ count : 0 , increment : () => set ((state) => ({ count: state.count + 1 })), })) // 在组件中使用 function Counter ( ) { const count = useStore( ( state ) => state.count) const increment = useStore( ( state ) => state.increment) return < button onClick = {increment} > {count} button > } 2. 灵活的状态订阅 Zustand 允许组件只订阅它们需要的状态片段,从而优化性能: // 只订阅特定字段 const userName = useStore( state => state.user.name) const
………………………………