Skip to content

Commit

Permalink
docs: add an example for setting the state outside event (#302) (#303)
Browse files Browse the repository at this point in the history
* feat(docs): add an example for setting the state outside event (#302)

* fix gramar issues

* Point more details URL to the issue instead of the tweet

* Simplify example

Co-authored-by: Daishi Kato <dai-shi@users.noreply.github.com>

* Update readme.md

* Update readme.md

Co-authored-by: Cristian Ratoi <cristian.ratoi@everymatrix.com>
Co-authored-by: Daishi Kato <dai-shi@users.noreply.github.com>
  • Loading branch information
3 people authored Feb 11, 2021
1 parent b3104dd commit c31c710
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,28 @@ 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`
```jsx
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
```jsx
Expand Down

0 comments on commit c31c710

Please sign in to comment.