zustand/docs/guides/event-handler-in-pre-react-18.md
Jacob Bergholtz 4ed81bc11b
Add usage with context to docs (#1291)
* docs: context guide proposal

* fix(docs): typo & omit comment

* fix(docs): remove horizontal rules

* fix(docs): add wiki link to DI

* fix(docs): format with prettier

* fix(docs): cases that model => where... is needed

* fix(docs): use sentence case

* fix(docs): omit quote block

* fix(docs): into "a" custom hook

* fix(docs): format with prettier

* fix(docs): sort broken nav indexes

* Update docs/guides/initialize-state-with-props.md

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

* fix(docs): reintroduce React.createContext example

* scripts: escape quotes

* styles: run prettier

* fix(docs): omit 'React' from imports

* styles: run prettier

* styles: run prettier

Co-authored-by: Daishi Kato <dai-shi@users.noreply.github.com>
2022-09-18 09:01:06 +09:00

827 B

title nav
Calling actions outside a React event handler in pre React 18 10

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, there is a risk of encountering the zombie-child effect. In order to fix this, the action needs to be wrapped in unstable_batchedUpdates like so:

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

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

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

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