Passing Function To setState()
Problem
// assuming this.state.count === 0
this.setState({count: this.state.count + 1});
this.setState({count: this.state.count + 1});
this.setState({count: this.state.count + 1});
// this.state.count === 1, not 3Solution
this.setState((prevState, props) => ({
count: prevState.count + props.increment
}));Variations
// Passing object
this.setState({ expanded: !this.state.expanded });
// Passing function
this.setState(prevState => ({ expanded: !prevState.expanded }));Related links:
Last updated