Fix odd state on load using React DOM batchedUpdates #42
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Hey!
This fixes #38 .
I spent some time investigating this and I figured out, as you suggested it, that it was the two consequent calls to
setState
that were not being batched by React. These 2 setState are triggering 2 separate renders, creating an odd state.This is a known "issue" in React, see facebook/react#17048
The workaround is to use the
ReactDOM.unstable_batchedUpdates
function that forces updates to be batched.There are numbers of scenarios where this is needed, like to a 404 page or a "no result" state on a search feature.
Another solution would be to use
useReducer
instead of multiplesetState
to do multiple state changes in a single render.One cons of this solution is that this relies on a React-DOM API which makes the code unusable in a React-Native environment.
Let me know what you think, thanks!