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

setState() callback function: potential confusion of call order #691

Open
danburzo opened this issue Mar 16, 2018 · 0 comments
Open

setState() callback function: potential confusion of call order #691

danburzo opened this issue Mar 16, 2018 · 0 comments

Comments

@danburzo
Copy link
Contributor

danburzo commented Mar 16, 2018

This paragraph from the React.Component reference page:

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied.

can create the impression that instead of doing:

this.setState({ value: 5 });
console.log(this.state.value); // => not necessarily 5

you can use the callback function to safely read the state back:

this.setState({ value: 5 }, () => console.log(this.state.value)); // => "guaranteed" 5

(especially if you draw a parallel between the callback function and the updater function)

and it may actually work in some cases where there's no setState batching, but as more calls get batched in the future, these constructs may generate unintended side-effects.

Instead, we could clarify that all callback functions for a batch of setState() calls get called after the entire batch has been processed.

@danburzo danburzo changed the title setState() callback function potential confusion of call order. setState() callback function: potential confusion of call order Mar 16, 2018
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