React setState callback function

setState in React is a function. It is accessible within the component and updates the state which then triggers the render-ing of the component with the updated state data.

However, React setState does not ensure re-rendering immediately as it is called, resulting in the rendering of data with previous state data. we can think of setState as a request for rendering the component which may get stuck or delay due to any of the reasons of react - redux lifecycle or a bugged code. An example of can be

// assuming state.count === 0
this.setState({count: state.count + 1});
this.setState({count: state.count + 1});
this.setState({count: state.count + 1});
// state.count === 1, not 3

So to overcome and ensure updated state data is used in next execution we use callback function of setState.

setState()

setState(updater[, callback])

Now the problem of further execution, after setState with updated state data is resolved by the callback function. The callback function uses the data which is set in this instance of setState and thus ensures updated data usage.

// state.count === 0
this.setState({count: state.count + 1}, () => {
this.setState({count: state.count + 1}, () => {
this.setState({count: state.count + 1}, () => {
// state.count === 3
});
});
});

 

This is a valid solution to previous code but it will slow down the execution and never used. It is just an example and not at all a practical scenario. You must understand working idea how the callback is implemented.

Hope this article clears the understanding of callback function usage.

excellence-social-linkdin
excellence-social-facebook
excellence-social-instagram
excellence-social-skype