Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: add an example for setting the state outside event (#302) #303

Merged
merged 6 commits into from
Feb 11, 2021
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,34 @@ 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 create from 'zustand'
import { unstable_batchedUpdates } from 'react-dom';

export const useStore = create(persist(
(set) => ({
fishes: 0,
addAFish: () => set({ fish: get().fish + 1 })
}),
))

const addAFish = useStore((state) => state.addAFish)

async function onClickHandler() {
await asyncFunc()
unstable_batchedUpdates(() => {
addAFish()
})
}
ratoi-crysty marked this conversation as resolved.
Show resolved Hide resolved
```

More details: https://twitter.com/dan_abramov/status/959507572951797761
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure how this is helpful. Remove it or replace the link to #302 and add the twitter link there?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK


## Redux devtools

```jsx
Expand Down