0
点赞
收藏
分享

微信扫一扫

Zustand:极简React状态管理


为什么选Zustand?

  • 比Redux简单,比Context高效
  • 无Provider包裹需求
  • 自动渲染优化
  • 支持TS类型

基础用法

npm install zustand

创建store:

// counterStore.ts
import { create } from 'zustand'

export const useCounterStore = create((set) => ({
  count: 0,
  increment: () => set(state => ({ count: state.count + 1 })),
  reset: () => set({ count: 0 })
}))

组件中使用:

function Counter() {
  const { count, increment } = useCounterStore()
  return (
    <div>
      <span>{count}</span>
      <button onClick={increment}>+1</button>
    </div>
  )
}

高级技巧

  1. 选择性订阅(优化性能):

const count = useCounterStore(state => state.count)

  1. 异步操作:

// store中
fetchData: async () => {
  set({ loading: true })
  const data = await api.getData()
  set({ data, loading: false })
}

  1. 持久化:

import { persist } from 'zustand/middleware'

create(persist(() => ({...}), {
  name: 'storage-key'
}))

Zustand以极简API提供了完整的状态管理方案,特别适合中小型React应用。

举报

相关推荐

0 条评论