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 ?