How to force the state update to take place in React after calling setState?
As far as I know, state is effectively updated when render is called next time. Also, forceUpdate()
should re-render the component and update the state changes immediately, right? However this doesn't seem to be the case. Here's an example.
handleSomeEvent(data) {
this.setState({
data: data
})
this.forceUpdate()
// At this point state should be updated but it isn't
this.props.consumeData(this.state.data) // consumeData will receive old data
}
How do I ensure state is actually updated before calling consumeData?
Forcing an update on a React class component In any user or system event, you can call the method this. forceUpdate() , which will cause render() to be called on the component, skipping shouldComponentUpdate() , and thus, forcing React to re-evaluate the Virtual DOM and DOM state.
To update state in React components, we'll use either the this. setState function or the updater function returned by the React. useState() Hook in class and function components, respectively.
Class ComponentsThe setState() method already allows us to pass a callback function (second argument) that runs once setState is done with updating the state and the component has re-rendered.
The first and most commonly used method to run a function after updating state is the useEffect hook. useEffect runs its function only when the items in the dependency array change.
setState()
is asynchronous, so you can do it in the callback:
handleSomeEvent(data) {
this.setState({
data: data
}, () => this.props.consumeData(this.state.data)); // using `data` would work as well...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With