Zustand 状态管理

安装

npx shadcn@latest add https://ssp-ui-registry-staging.sh3.agoralab.co/r/zustand.json
yarn dlx shadcn@latest add https://ssp-ui-registry-staging.sh3.agoralab.co/r/zustand.json
pnpx shadcn@latest add https://ssp-ui-registry-staging.sh3.agoralab.co/r/zustand.json
bunx shadcn@latest add https://ssp-ui-registry-staging.sh3.agoralab.co/r/zustand.json

参考

示例代码

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

// 用slice方式组织store

type TUserInfoSlice = {
  user: string | null
  updateUser: (user: string | null) => void
}

type TPreferenceSlice = {
  pagination: {
    pageSize: number
  }
  updatePagination: (pagination: { pageSize: number }) => void
}

type TGlobalStore = TUserInfoSlice & TPreferenceSlice

const createUserInfoSlice: StateCreator<
  TGlobalStore,
  [['zustand/devtools', never]],
  [],
  TUserInfoSlice
> = (set) => ({
  user: null,
  updateUser: (user) => set({ user })
})

const createPreferenceSlice: StateCreator<
  TGlobalStore,
  [['zustand/devtools', never]],
  [],
  TPreferenceSlice
> = (set) => ({
  pagination: {
    pageSize: 10
  },
  updatePagination: (pagination) => set({ pagination })
})

export const useGlobalStore = create<TGlobalStore>()(
  // 使用devtools和persist中间件
  // devtools用来支持redux devtools插件调试
  // persist用来持久化部分store数据到localStorage(或其他存储介质)
  devtools(
    persist(
      (...args) => ({
        ...createUserInfoSlice(...args),
        ...createPreferenceSlice(...args)
      }),
      {
        name: 'global-store', // storage key
        partialize: (state) => ({
          pagination: state.pagination
        }),
        version: 1
        // handle here if migration is needed
        // migrate: (persisted, version) => persisted,
      }
    ),
    { name: 'GlobalStore' }
  )
)