@abraaoz/zustand 中文文档教程

发布于 3年前 浏览 29 项目主页 更新于 3年前

构建状态构建大小版本下载Discord Shield

一种小型、快速且可扩展的 bearbones 状态管理解决方案,使用简化的通量原理。 有一个基于钩子的舒适 api,不是样板文件或固执己见。

不要因为它可爱而忽视它。 它有很多爪子,花了很多时间来处理常见的陷阱,比如可怕的 僵尸儿童问题反应并发 ,以及混合渲染器之间的上下文丢失。 它可能是 React 空间中的唯一状态管理器,可以正确处理所有这些问题。

您可以在此处尝试现场演示。

npm install zustand@npm:@abraaoz/zustand # or yarn add zustand@npm:@abraaoz/zustand

Fork motivation

这是 https://github.com/pmndrs/zustand 的一个分支。 此分支允许您导入以下 TypeScript 定义:

import {
  Combine,
  DeepPartial,
  StorageValue,
  PersistOptions,
} from 'zustand/middleware'

要在 npm 上发布新版本,请运行 npm version (xyz)-with-typesyarn buildcd dist 然后 npm publish --access public

First create a store

你的商店是一个钩子! 您可以在其中放入任何东西:基元、对象、函数。 set 函数 merges 状态。

import create from 'zustand'

const useStore = create(set => ({
  bears: 0,
  increasePopulation: () => set(state => ({ bears: state.bears + 1 })),
  removeAllBears: () => set({ bears: 0 })
}))

Then bind your components, and that's it!

在任何地方使用挂钩,不需要提供者。 选择您的状态,组件将根据更改重新呈现。

function BearCounter() {
  const bears = useStore(state => state.bears)
  return <h1>{bears} around here ...</h1>
}

function Controls() {
  const increasePopulation = useStore(state => state.increasePopulation)
  return <button onClick={increasePopulation}>one up</button>
}

Why zustand over redux?

Why zustand over context?

  • Less boilerplate
  • Renders components only on changes
  • Centralized, action-based state management

Recipes

Fetching everything

您可以,但请记住,它会导致组件在每次状态更改时更新!

const state = useStore()

Selecting multiple state slices

它默认检测严格相等的变化(旧的===新的),这对于原子状态选择是有效的。

const nuts = useStore(state => state.nuts)
const honey = useStore(state => state.honey)

如果你想构造一个内部有多个状态选择的单个对象,类似于 redux 的 mapStateToProps,你可以告诉 zustand 你希望通过传递 shallow 相等函数来浅区分对象。

import shallow from 'zustand/shallow'

// Object pick, re-renders the component when either state.nuts or state.honey change
const { nuts, honey } = useStore(state => ({ nuts: state.nuts, honey: state.honey }), shallow)

// Array pick, re-renders the component when either state.nuts or state.honey change
const [nuts, honey] = useStore(state => [state.nuts, state.honey], shallow)

// Mapped picks, re-renders the component when state.treats changes in order, count or keys
const treats = useStore(state => Object.keys(state.treats), shallow)

为了更好地控制重新渲染,您可以提供任何自定义相等函数。

const treats = useStore(
  state => state.treats,
  (oldTreats, newTreats) => compare(oldTreats, newTreats)
)

Memoizing selectors

通常建议使用 useCallback 来记忆选择器。 这将防止每次渲染都进行不必要的计算。 它还允许 React 在并发模式下优化性能。

const fruit = useStore(useCallback(state => state.fruits[id], [id]))

如果一个选择器不依赖于作用域,你可以在 render 函数之外定义它来获得一个固定的引用而不需要 useCallback。

const selector = state => state.berries

function Component() {
  const berries = useStore(selector)

Overwriting state

set 函数有第二个参数,默认为 false。 它将取代状态模型,而不是合并。 小心不要擦掉你依赖的部分,比如动作。

import omit from "lodash-es/omit"

const useStore = create(set => ({
  salmon: 1,
  tuna: 2,
  deleteEverything: () => set({ }, true), // clears the entire store, actions included
  deleteTuna: () => set(state => omit(state, ['tuna']), true)
}))

Async actions

准备就绪后只需调用 set,zustand 不关心您的操作是否异步。

const useStore = create(set => ({
  fishies: {},
  fetch: async pond => {
    const response = await fetch(pond)
    set({ fishies: await response.json() })
  }
}))

Read from state in actions

set 允许 fn-updates set(state => result),但您仍然可以通过 get 访问它之外的状态。

const useStore = create((set, get) => ({
  sound: "grunt",
  action: () => {
    const sound = get().sound
    // ...
  }
})

Reading/writing state and reacting to changes outside of components

有时您需要以非反应性方式访问状态,或对商店采取行动。 对于这些情况,生成的钩子具有附加到其原型的实用函数。

const useStore = create(() => ({ paw: true, snout: true, fur: true }))

// Getting non-reactive fresh state
const paw = useStore.getState().paw
// Listening to all changes, fires on every change
const unsub1 = useStore.subscribe(console.log)
// Listening to selected changes, in this case when "paw" changes
const unsub2 = useStore.subscribe(console.log, state => state.paw)
// Subscribe also supports an optional equality function
const unsub3 = useStore.subscribe(console.log, state => [state.paw, state.fur], shallow)
// Subscribe also exposes the previous value
const unsub4 = useStore.subscribe((paw, previousPaw) => console.log(paw, previousPaw), state => state.paw)
// Updating state, will trigger listeners
useStore.setState({ paw: false })
// Unsubscribe listeners
unsub1()
unsub2()
unsub3()
unsub4()
// Destroying the store (removing all listeners)
useStore.destroy()

// You can of course use the hook as you always would
function Component() {
  const paw = useStore(state => state.paw)

Using zustand without React

Zustands 核心可以在没有 React 依赖的情况下导入和使用。 唯一的区别是 create 函数不返回钩子,而是返回 api 实用程序。

import create from 'zustand/vanilla'

const store = create(() => ({ ... }))
const { getState, setState, subscribe, destroy } = store

您甚至可以使用 React 消费现有的香草商店

import create from 'zustand'
import vanillaStore from './vanillaStore'

const useStore = create(vanillaStore)

::警告:请注意,修改 setget 的中间件不适用于 getState 和 <代码>设置状态。

Transient updates (for often occuring state-changes)

订阅功能允许组件绑定到状态部分,而无需强制重新渲染更改。 最好将它与 useEffect 结合使用,以便在卸载时自动取消订阅。 当您被允许直接改变视图时,这可能会对性能产生剧烈的影响。

const useStore = create(set => ({ scratches: 0, ... }))

function Component() {
  // Fetch initial state
  const scratchRef = useRef(useStore.getState().scratches)
  // Connect to the store on mount, disconnect on unmount, catch state-changes in a reference
  useEffect(() => useStore.subscribe(
    scratches => (scratchRef.current = scratches),
    state => state.scratches
  ), [])

Sick of reducers and changing nested state? Use Immer!

减少嵌套结构很烦人。 您是否尝试过 immer

import produce from 'immer'

const useStore = create(set => ({
  lush: { forest: { contains: { a: "bear" } } },
  clearForest: () => set(produce(state => {
    state.lush.forest.contains = null
  }))
}))

const clearForest = useStore(state => state.clearForest)
clearForest();

Middleware

您可以按照自己喜欢的方式在功能上组合您的商店。

// Log every time state is changed
const log = config => (set, get, api) => config(args => {
  console.log("  applying", args)
  set(args)
  console.log("  new state", get())
}, get, api)

// Turn the set method into an immer proxy
const immer = config => (set, get, api) => config((partial, replace) => {
  const nextState = typeof partial === 'function'
      ? produce(partial)
      : partial
  return set(nextState, replace)
}, get, api)

const useStore = create(
  log(
    immer((set) => ({
      bees: false,
      setBees: (input) => set((state) => void (state.bees = input)),
    })),
  ),
)

How to pipe middlewares

import create from "zustand"
import produce from "immer"
import pipe from "ramda/es/pipe"

/* log and immer functions from previous example */
/* you can pipe as many middlewares as you want */
const createStore = pipe(log, immer, create)

const useStore = createStore(set => ({
  bears: 1,
  increasePopulation: () => set(state => ({ bears: state.bears + 1 }))
}))

export default useStore

有关 TS 示例,请参阅以下讨论

How to type immer middleware in TypeScript

import { State, StateCreator } from 'zustand'
import produce, { Draft } from 'immer'

const immer = <T extends State>(config: StateCreator<T>): StateCreator<T> => 
  (set, get, api) => config((partial, replace) => {
    const nextState =
      typeof partial === 'function'
        ? produce(partial as (state: Draft<T>) => T)
        : partial as T
    return set(nextState, replace)
  }, get, api)

Persist middleware

您可以使用任何类型的存储来保存商店的数据。

import create from "zustand"
import { persist } from "zustand/middleware"

export const useStore = create(persist(
  (set, get) => ({
    fishes: 0,
    addAFish: () => set({ fishes: get().fishes + 1 })
  }),
  {
    name: "food-storage", // unique name
    getStorage: () => sessionStorage, // (optional) by default the 'localStorage' is used
  }
))

How to use custom storage engines

您可以通过定义自己的 StateStorage 使用 localStoragesessionStorage 之外的其他存储方法。 自定义 StateStorage 对象还允许您在获取或设置存储数据时为持久化存储编写中间件。

import create from "zustand"
import { persist, StateStorage } from "zustand/middleware"
import { get, set } from 'idb-keyval' // can use anything: IndexedDB, Ionic Storage, etc.

// Custom storage object
const storage: StateStorage = {
  getItem: async (name: string): Promise<string | null> => {
    console.log(name, "has been retrieved");
    return await get(name) || null
  },
  setItem: async (name: string, value: string): Promise<void> => {
    console.log(name, "with value", value, "has been saved");
    set(name, value)
  }
}

export const useStore = create(persist(
  (set, get) => ({
    fishes: 0,
    addAFish: () => set({ fishes: get().fishes + 1 })
  }),
  {
    name: "food-storage", // unique name
    getStorage: () => storage,
  }
))

Can't live without redux-like reducers and action types?

const types = { increase: "INCREASE", decrease: "DECREASE" }

const reducer = (state, { type, by = 1 }) => {
  switch (type) {
    case types.increase: return { grumpiness: state.grumpiness + by }
    case types.decrease: return { grumpiness: state.grumpiness - by }
  }
}

const useStore = create(set => ({
  grumpiness: 0,
  dispatch: args => set(state => reducer(state, args)),
}))

const dispatch = useStore(state => state.dispatch)
dispatch({ type: types.increase, by: 2 })

或者,只需使用我们的 redux-middleware。 它连接你的 main-reducer,设置初始状态,并为状态本身和 vanilla api 添加一个调度函数。 试试这个例子。

import { redux } from 'zustand/middleware'

const useStore = create(redux(reducer, initialState))

Calling actions outside a React event handler

因为如果在事件处理程序之外调用 React,它会同步处理 setState。 在事件处理程序之外更新状态将强制 React 同步更新组件,因此增加了遇到 zombie-child effect 的风险。 为了解决这个问题,需要将操作包装在 unstable_batchedUpdates

import { unstable_batchedUpdates } from 'react-dom' // or 'react-native'

const useStore = create((set) => ({
  fishes: 0,
  increaseFishes: () => set((prev) => ({ fishes: prev.fishes + 1 }))
}))

const nonReactCallback = () => {
  unstable_batchedUpdates(() => {
    useStore.getState().increaseFishes()
  })
}

更多详细信息:https://github.com/pmndrs/zustand/issues/302

Redux devtools

import { devtools } from 'zustand/middleware'

// Usage with a plain action store, it will log actions as "setState"
const useStore = create(devtools(store))
// Usage with a redux store, it will log full action types
const useStore = create(devtools(redux(reducer, initialState)))

devtools 将存储函数作为其第一个参数,可选您可以命名商店或配置 serialize 选项第二个论点。

名称存储:devtools(store, {name: "MyStore"}),它将作为您操作的前缀。
序列化选项:devtools(store, { serialize: { options: true } })

devtools 将只记录来自每个单独存储的操作,这与典型的 combined reducers redux 存储不同。 查看组合商店的方法 https://github.com/pmndrs/zustand/issues/163

React context

使用 create 创建的商店不需要上下文提供程序。 在某些情况下,您可能希望使用上下文进行依赖注入,或者如果您想使用组件中的 props 初始化商店。 因为商店是一个钩子,将其作为普通上下文值传递可能会违反钩子规则。 为了避免误用,提供了一个特殊的 createContext

import create from 'zustand'
import createContext from 'zustand/context'

const { Provider, useStore } = createContext()

const createStore = () => create(...)

const App = () => (
  <Provider createStore={createStore}>
    ...
  </Provider>
)

const Component = () => {
  const state = useStore()
  const slice = useStore(selector)
  ...
}

createContext usage in real components

  import create from "zustand";
  import createContext from "zustand/context";

  // Best practice: You can move the below createContext() and createStore to a separate file(store.js) and import the Provider, useStore here/wherever you need.

  const { Provider, useStore } = createContext();

  const createStore = () =>
    create((set) => ({
      bears: 0,
      increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
      removeAllBears: () => set({ bears: 0 })
    }));

  const Button = () => {
    return (
        {/** store() - This will create a store for each time using the Button component instead of using one store for all components **/}
      <Provider createStore={createStore}> 
        <ButtonChild />
      </Provider>
    );
  };

  const ButtonChild = () => {
    const state = useStore();
    return (
      <div>
        {state.bears}
        <button
          onClick={() => {
            state.increasePopulation();
          }}
        >
          +
        </button>
      </div>
    );
  };

  export default function App() {
    return (
      <div className="App">
        <Button />
        <Button />
      </div>
    );
  }

createContext usage with initialization from props (in TypeScript)

  import create from "zustand";
  import createContext from "zustand/context";

  type BearState = {
    bears: number
    increase: () => void
  }

  // pass the type to `createContext` rather than to `create`
  const { Provider, useStore } = createContext<BearState>();

  export default function App({ initialBears }: { initialBears: number }) {
    return (
      <Provider
        createStore={() =>
          create((set) => ({
            bears: initialBears,
            increase: () => set((state) => ({ bears: state.bears + 1 })),
          }))
        }
      >
        <Button />
      </Provider>
  )
}

Typing your store and combine middleware

// You can use `type`
type BearState = {
  bears: number
  increase: (by: number) => void
}

// Or `interface`
interface BearState {
  bears: number
  increase: (by: number) => void
}

// And it is going to work for both
const useStore = create<BearState>(set => ({
  bears: 0,
  increase: (by) => set(state => ({ bears: state.bears + by })),
}))

或者,使用 combine 并让 tsc 推断类型。 这浅合并了两个状态。

import { combine } from 'zustand/middleware'

const useStore = create(
  combine(
    { bears: 0 },
    (set) => ({ increase: (by: number) => set((state) => ({ bears: state.bears + by })) })
  ),
)

Best practices

Testing

有关使用 Zustand 进行测试的信息,请访问专门的 Wiki 页面

3rd-Party Libraries

一些用户可能想要扩展 Zustand 的功能集,这可以使用社区制作的第 3 方库来完成。 有关 Zustand 的第 3 方库的信息,请访问专门的 Wiki 页面

Comparison with other libraries

Build StatusBuild SizeVersionDownloadsDiscord Shield

A small, fast and scalable bearbones state-management solution using simplified flux principles. Has a comfy api based on hooks, isn't boilerplatey or opinionated.

Don't disregard it because it's cute. It has quite the claws, lots of time was spent to deal with common pitfalls, like the dreaded zombie child problem, react concurrency, and context loss between mixed renderers. It may be the one state-manager in the React space that gets all of these right.

You can try a live demo here.

npm install zustand@npm:@abraaoz/zustand # or yarn add zustand@npm:@abraaoz/zustand

Fork motivation

This is a fork of https://github.com/pmndrs/zustand. This fork allows you to import the following TypeScript definitions:

import {
  Combine,
  DeepPartial,
  StorageValue,
  PersistOptions,
} from 'zustand/middleware'

To publish a new version at npm, run npm version (x.y.z)-with-types, yarn build, cd dist then npm publish --access public.

First create a store

Your store is a hook! You can put anything in it: primitives, objects, functions. The set function merges state.

import create from 'zustand'

const useStore = create(set => ({
  bears: 0,
  increasePopulation: () => set(state => ({ bears: state.bears + 1 })),
  removeAllBears: () => set({ bears: 0 })
}))

Then bind your components, and that's it!

Use the hook anywhere, no providers needed. Select your state and the component will re-render on changes.

function BearCounter() {
  const bears = useStore(state => state.bears)
  return <h1>{bears} around here ...</h1>
}

function Controls() {
  const increasePopulation = useStore(state => state.increasePopulation)
  return <button onClick={increasePopulation}>one up</button>
}

Why zustand over redux?

Why zustand over context?

  • Less boilerplate
  • Renders components only on changes
  • Centralized, action-based state management

Recipes

Fetching everything

You can, but bear in mind that it will cause the component to update on every state change!

const state = useStore()

Selecting multiple state slices

It detects changes with strict-equality (old === new) by default, this is efficient for atomic state picks.

const nuts = useStore(state => state.nuts)
const honey = useStore(state => state.honey)

If you want to construct a single object with multiple state-picks inside, similar to redux's mapStateToProps, you can tell zustand that you want the object to be diffed shallowly by passing the shallow equality function.

import shallow from 'zustand/shallow'

// Object pick, re-renders the component when either state.nuts or state.honey change
const { nuts, honey } = useStore(state => ({ nuts: state.nuts, honey: state.honey }), shallow)

// Array pick, re-renders the component when either state.nuts or state.honey change
const [nuts, honey] = useStore(state => [state.nuts, state.honey], shallow)

// Mapped picks, re-renders the component when state.treats changes in order, count or keys
const treats = useStore(state => Object.keys(state.treats), shallow)

For more control over re-rendering, you may provide any custom equality function.

const treats = useStore(
  state => state.treats,
  (oldTreats, newTreats) => compare(oldTreats, newTreats)
)

Memoizing selectors

It is generally recommended to memoize selectors with useCallback. This will prevent unnecessary computations each render. It also allows React to optimize performance in concurrent mode.

const fruit = useStore(useCallback(state => state.fruits[id], [id]))

If a selector doesn't depend on scope, you can define it outside the render function to obtain a fixed reference without useCallback.

const selector = state => state.berries

function Component() {
  const berries = useStore(selector)

Overwriting state

The set function has a second argument, false by default. Instead of merging, it will replace the state model. Be careful not to wipe out parts you rely on, like actions.

import omit from "lodash-es/omit"

const useStore = create(set => ({
  salmon: 1,
  tuna: 2,
  deleteEverything: () => set({ }, true), // clears the entire store, actions included
  deleteTuna: () => set(state => omit(state, ['tuna']), true)
}))

Async actions

Just call set when you're ready, zustand doesn't care if your actions are async or not.

const useStore = create(set => ({
  fishies: {},
  fetch: async pond => {
    const response = await fetch(pond)
    set({ fishies: await response.json() })
  }
}))

Read from state in actions

set allows fn-updates set(state => result), but you still have access to state outside of it through get.

const useStore = create((set, get) => ({
  sound: "grunt",
  action: () => {
    const sound = get().sound
    // ...
  }
})

Reading/writing state and reacting to changes outside of components

Sometimes you need to access state in a non-reactive way, or act upon the store. For these cases the resulting hook has utility functions attached to its prototype.

const useStore = create(() => ({ paw: true, snout: true, fur: true }))

// Getting non-reactive fresh state
const paw = useStore.getState().paw
// Listening to all changes, fires on every change
const unsub1 = useStore.subscribe(console.log)
// Listening to selected changes, in this case when "paw" changes
const unsub2 = useStore.subscribe(console.log, state => state.paw)
// Subscribe also supports an optional equality function
const unsub3 = useStore.subscribe(console.log, state => [state.paw, state.fur], shallow)
// Subscribe also exposes the previous value
const unsub4 = useStore.subscribe((paw, previousPaw) => console.log(paw, previousPaw), state => state.paw)
// Updating state, will trigger listeners
useStore.setState({ paw: false })
// Unsubscribe listeners
unsub1()
unsub2()
unsub3()
unsub4()
// Destroying the store (removing all listeners)
useStore.destroy()

// You can of course use the hook as you always would
function Component() {
  const paw = useStore(state => state.paw)

Using zustand without React

Zustands core can be imported and used without the React dependency. The only difference is that the create function does not return a hook, but the api utilities.

import create from 'zustand/vanilla'

const store = create(() => ({ ... }))
const { getState, setState, subscribe, destroy } = store

You can even consume an existing vanilla store with React:

import create from 'zustand'
import vanillaStore from './vanillaStore'

const useStore = create(vanillaStore)

:warning: Note that middlewares that modify set or get are not applied to getState and setState.

Transient updates (for often occuring state-changes)

The subscribe function allows components to bind to a state-portion without forcing re-render on changes. Best combine it with useEffect for automatic unsubscribe on unmount. This can make a drastic performance impact when you are allowed to mutate the view directly.

const useStore = create(set => ({ scratches: 0, ... }))

function Component() {
  // Fetch initial state
  const scratchRef = useRef(useStore.getState().scratches)
  // Connect to the store on mount, disconnect on unmount, catch state-changes in a reference
  useEffect(() => useStore.subscribe(
    scratches => (scratchRef.current = scratches),
    state => state.scratches
  ), [])

Sick of reducers and changing nested state? Use Immer!

Reducing nested structures is tiresome. Have you tried immer?

import produce from 'immer'

const useStore = create(set => ({
  lush: { forest: { contains: { a: "bear" } } },
  clearForest: () => set(produce(state => {
    state.lush.forest.contains = null
  }))
}))

const clearForest = useStore(state => state.clearForest)
clearForest();

Middleware

You can functionally compose your store any way you like.

// Log every time state is changed
const log = config => (set, get, api) => config(args => {
  console.log("  applying", args)
  set(args)
  console.log("  new state", get())
}, get, api)

// Turn the set method into an immer proxy
const immer = config => (set, get, api) => config((partial, replace) => {
  const nextState = typeof partial === 'function'
      ? produce(partial)
      : partial
  return set(nextState, replace)
}, get, api)

const useStore = create(
  log(
    immer((set) => ({
      bees: false,
      setBees: (input) => set((state) => void (state.bees = input)),
    })),
  ),
)

How to pipe middlewares

import create from "zustand"
import produce from "immer"
import pipe from "ramda/es/pipe"

/* log and immer functions from previous example */
/* you can pipe as many middlewares as you want */
const createStore = pipe(log, immer, create)

const useStore = createStore(set => ({
  bears: 1,
  increasePopulation: () => set(state => ({ bears: state.bears + 1 }))
}))

export default useStore

For a TS example see the following discussion

How to type immer middleware in TypeScript

import { State, StateCreator } from 'zustand'
import produce, { Draft } from 'immer'

const immer = <T extends State>(config: StateCreator<T>): StateCreator<T> => 
  (set, get, api) => config((partial, replace) => {
    const nextState =
      typeof partial === 'function'
        ? produce(partial as (state: Draft<T>) => T)
        : partial as T
    return set(nextState, replace)
  }, get, api)

Persist middleware

You can persist your store's data using any kind of storage.

import create from "zustand"
import { persist } from "zustand/middleware"

export const useStore = create(persist(
  (set, get) => ({
    fishes: 0,
    addAFish: () => set({ fishes: get().fishes + 1 })
  }),
  {
    name: "food-storage", // unique name
    getStorage: () => sessionStorage, // (optional) by default the 'localStorage' is used
  }
))

How to use custom storage engines

You can use other storage methods outside of localStorage and sessionStorage by defining your own StateStorage. A custom StateStorage object also allows you to write middlware for the persisted store when getting or setting store data.

import create from "zustand"
import { persist, StateStorage } from "zustand/middleware"
import { get, set } from 'idb-keyval' // can use anything: IndexedDB, Ionic Storage, etc.

// Custom storage object
const storage: StateStorage = {
  getItem: async (name: string): Promise<string | null> => {
    console.log(name, "has been retrieved");
    return await get(name) || null
  },
  setItem: async (name: string, value: string): Promise<void> => {
    console.log(name, "with value", value, "has been saved");
    set(name, value)
  }
}

export const useStore = create(persist(
  (set, get) => ({
    fishes: 0,
    addAFish: () => set({ fishes: get().fishes + 1 })
  }),
  {
    name: "food-storage", // unique name
    getStorage: () => storage,
  }
))

Can't live without redux-like reducers and action types?

const types = { increase: "INCREASE", decrease: "DECREASE" }

const reducer = (state, { type, by = 1 }) => {
  switch (type) {
    case types.increase: return { grumpiness: state.grumpiness + by }
    case types.decrease: return { grumpiness: state.grumpiness - by }
  }
}

const useStore = create(set => ({
  grumpiness: 0,
  dispatch: args => set(state => reducer(state, args)),
}))

const dispatch = useStore(state => state.dispatch)
dispatch({ type: types.increase, by: 2 })

Or, just use our redux-middleware. It wires up your main-reducer, sets initial state, and adds a dispatch function to the state itself and the vanilla api. Try this example.

import { redux } from 'zustand/middleware'

const useStore = create(redux(reducer, initialState))

Calling actions outside a React event handler

Because React handles setState synchronously if it's called outside an event handler. Updating the state outside an event handler will force react to update the components synchronously, therefore adding the risk of encountering the zombie-child effect. In order to fix this, the action needs to be wrapped in unstable_batchedUpdates

import { unstable_batchedUpdates } from 'react-dom' // or 'react-native'

const useStore = create((set) => ({
  fishes: 0,
  increaseFishes: () => set((prev) => ({ fishes: prev.fishes + 1 }))
}))

const nonReactCallback = () => {
  unstable_batchedUpdates(() => {
    useStore.getState().increaseFishes()
  })
}

More details: https://github.com/pmndrs/zustand/issues/302

Redux devtools

import { devtools } from 'zustand/middleware'

// Usage with a plain action store, it will log actions as "setState"
const useStore = create(devtools(store))
// Usage with a redux store, it will log full action types
const useStore = create(devtools(redux(reducer, initialState)))

devtools takes the store function as its first argument, optionally you can name the store or configure serialize options with a second argument.

Name store: devtools(store, {name: "MyStore"}), which will be prefixed to your actions.
Serialize options: devtools(store, { serialize: { options: true } }).

devtools will only log actions from each separated store unlike in a typical combined reducers redux store. See an approach to combining stores https://github.com/pmndrs/zustand/issues/163

React context

The store created with create doesn't require context providers. In some cases, you may want to use contexts for dependency injection or if you want to initialize your store with props from a component. Because the store is a hook, passing it as a normal context value may violate rules of hooks. To avoid misusage, a special createContext is provided.

import create from 'zustand'
import createContext from 'zustand/context'

const { Provider, useStore } = createContext()

const createStore = () => create(...)

const App = () => (
  <Provider createStore={createStore}>
    ...
  </Provider>
)

const Component = () => {
  const state = useStore()
  const slice = useStore(selector)
  ...
}

createContext usage in real components

  import create from "zustand";
  import createContext from "zustand/context";

  // Best practice: You can move the below createContext() and createStore to a separate file(store.js) and import the Provider, useStore here/wherever you need.

  const { Provider, useStore } = createContext();

  const createStore = () =>
    create((set) => ({
      bears: 0,
      increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
      removeAllBears: () => set({ bears: 0 })
    }));

  const Button = () => {
    return (
        {/** store() - This will create a store for each time using the Button component instead of using one store for all components **/}
      <Provider createStore={createStore}> 
        <ButtonChild />
      </Provider>
    );
  };

  const ButtonChild = () => {
    const state = useStore();
    return (
      <div>
        {state.bears}
        <button
          onClick={() => {
            state.increasePopulation();
          }}
        >
          +
        </button>
      </div>
    );
  };

  export default function App() {
    return (
      <div className="App">
        <Button />
        <Button />
      </div>
    );
  }

createContext usage with initialization from props (in TypeScript)

  import create from "zustand";
  import createContext from "zustand/context";

  type BearState = {
    bears: number
    increase: () => void
  }

  // pass the type to `createContext` rather than to `create`
  const { Provider, useStore } = createContext<BearState>();

  export default function App({ initialBears }: { initialBears: number }) {
    return (
      <Provider
        createStore={() =>
          create((set) => ({
            bears: initialBears,
            increase: () => set((state) => ({ bears: state.bears + 1 })),
          }))
        }
      >
        <Button />
      </Provider>
  )
}

Typing your store and combine middleware

// You can use `type`
type BearState = {
  bears: number
  increase: (by: number) => void
}

// Or `interface`
interface BearState {
  bears: number
  increase: (by: number) => void
}

// And it is going to work for both
const useStore = create<BearState>(set => ({
  bears: 0,
  increase: (by) => set(state => ({ bears: state.bears + by })),
}))

Or, use combine and let tsc infer types. This merges two states shallowly.

import { combine } from 'zustand/middleware'

const useStore = create(
  combine(
    { bears: 0 },
    (set) => ({ increase: (by: number) => set((state) => ({ bears: state.bears + by })) })
  ),
)

Best practices

Testing

For information regarding testing with Zustand, visit the dedicated Wiki page.

3rd-Party Libraries

Some users may want to extends Zustand's feature set which can be done using 3rd-party libraries made by the community. For information regarding 3rd-party libraries with Zustand, visit the dedicated Wiki page.

Comparison with other libraries

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文