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

Too many rerenders when updating state async #3

Closed
andrewgreenh opened this issue Nov 15, 2019 · 0 comments
Closed

Too many rerenders when updating state async #3

andrewgreenh opened this issue Nov 15, 2019 · 0 comments

Comments

@andrewgreenh
Copy link

Problem
When calling the state setter from a place outside of react's scope (in a setTimeout, setInterval, after a network request, etc.), the update causes too many rerenders.
This can be seen in this CodeSandbox: https://codesandbox.io/s/simple-demo-e115u
1 click on the add button causes 6 rerenders of the bottom most ClickView

Reason
As the state is kept in each component instance, it needs to be updated. When the subscribed components happen to be nested as in our case (6 levels of nesting), 6 calls to setState happen.
As component effects run bottom to top, listeners are also registered bottom to top. That means, as we loop over all state setters here: https://github.com/pabra/react-hooksack/blob/master/src/index.ts#L44, we call the bottom most stateSetter first, causing a rerender of level 0 (bottom most). After this, setState is called on level 1, which causes a rerender of levels 1 and 0. After this, setState is called on level 2, which causes a rerender of levels 0, 1 and 2.

React's setState batches calls when called from a context in React (event handlers, effects, etc. for example). Which means, the problem does not happen when setting the global state from inside React. (all calls to setState are batched and only one render pass is needed). However, when we call the setState in a setTimeout, setState happens sync, which means, the waterfall can be observed.

Solution
react-redux is facing the same problem. They solved it by wrapping the stateSetters in ReactDOM.unstable_batchedUpdates.
This is defined here: https://github.com/reduxjs/react-redux/blob/master/src/utils/reactBatchedUpdates.js
And called here: https://github.com/reduxjs/react-redux/blob/master/src/utils/Subscription.js#L25

@pabra pabra closed this as completed in 95ccef2 Nov 16, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant