Skip to content

Too many rerenders when updating state async #3

Closed
@andrewgreenh

Description

@andrewgreenh

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions