Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: how to force state changes to take place after setState

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?

like image 518
Tuomas Toivonen Avatar asked Jul 07 '16 12:07

Tuomas Toivonen


People also ask

How do you force change state in React?

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.

How do you make state update immediately in React?

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.

Can I execute a function after setState is finished updating?

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.

How would you run code immediately after state has changed?

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.


1 Answers

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...
}
like image 143
Samuli Hakoniemi Avatar answered Oct 16 '22 23:10

Samuli Hakoniemi