Reputation: 112
In the article (https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html) from react docs, there is the following:
Refs can be useful in certain cases like this one, but generally we recommend you use them sparingly. Even in the demo, this imperative method is nonideal because two renders will occur instead of one..
here is a relevant part of the demo from https://codesandbox.io/s/l70krvpykl?file=/index.js:
handleChange = index => {
this.setState({ selectedIndex: index }, () => {
const selectedAccount = this.props.accounts[index];
this.inputRef.current.resetEmailForNewUser(selectedAccount.email);
});
};
i tweaked this demo, and i figured out a way to re-render just once like this (i delete the callback function because it runs after componentDidUpdate so it causes re-render twice):
handleChange = index => {
this.setState({ selectedIndex: index }); // set state of Parent Component (itself)
const selectedAccount = this.props.accounts[index];
this.inputRef.current.resetEmailForNewUser(selectedAccount.email); // set State of Child Component
};
i am wondering why this works and re-render just once. i thought maybe react batch both setState.
i am not sure why it's not recommended to do it like this ?
Upvotes: 2
Views: 78
Reputation: 2627
The use of the setState callback "guarantees" that this call back will only be executed after the state variables within the {} are updated:
this.setState({.... }, () => {to do only after state variables are updated})
In the second case you mentioned, there is no guarantee that this "sequential" execution will be respected. In this case you have no problems with parallelism respect of objects affected by the index parameter. However, if there are other components that depend on the "selectedIndex" state variable you could get into estrange problems depending a lot on how you structured them.
Upvotes: 1