zustand setState callback function

Viewed 32

I am just wondering if there is a way for zustand.setState function to be used just like the setState function in react like.

useStore().setState({ stateOne: (prevState) => ({ ...prevState, newProperty: 'value' })

currently the only way to use the setState is:

useStore().setState({ stateOne: { newProperty: 'value' })

thank you.

1 Answers

Yes, you can do that. Zustand also accepts a function as a parameter for setState.

import create from 'zustand'

const useFooBar = create(() => ({ foo: new Map(), bar: new Set() }))

function doSomething() {
  // doing something...

  // If you want to update some React component that uses `useFooBar`, you have to call setState
  // to let React know that an update happened.
  // Following React's best practices, you should create a new Map/Set when updating them:
  useFooBar.setState((prev) => ({
    foo: new Map(prev.foo).set('newKey', 'newValue'),
    bar: new Set(prev.bar).add('newKey'),
  }))
}

Here you can refer to zustand docs: https://docs.pmnd.rs/zustand/guides/maps-and-sets-usage

Related