MarcL
MarcL

Reputation: 3593

React.js: Will multiple async setState method calls always re-render after and impact performance?

I have seen a React setState method with a callback, which means that the callback will be executed after it is ensured that the new state has been set and the component was re-rendered, e.g this example:

this.setState({value: event.target.value}, function () {
    console.log(this.state.value);
}); //new state will be logged to console after it was set and rendered

now, if I am not totally wrong, the same thing can be implemented using async functions:

async someFunction(){
await this.setState({value: event.target.value});
console.log(this.state.value);
}

My question now is, will it impact performance if I use multiple await setState calls in one function? will it re-render after each setState call and wait for it to finish the rendering process, and then execute the net await setState call etc. and possibly create performance issues? e.g:

async someFunction(){
await this.setState({value: event.target.value});
let result = await someAPICall();
await this.setState({resultApiCall: result});
await.....
}

Upvotes: 4

Views: 2125

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138407

Yes, you are totally wrong :) setState does not return a promise, therefore you can't just await it. For sure you can wrap the callback into a promise, but you probably don't need that (as you usually don't need to wait for a rerender).

will it impact performance if I use multiple await setState calls in one function?

Sure. Calling a function twice is estimatedly twice as slow as calling it once.

will it re-render after each setState call and wait for it to finish the rendering process, and then [go on]?

Yes, if you would await a Promise, like this:

 await new Promise(resolve => this.setState(/*...*/, resolve));

and possibly create performance issues?

No, probably not. Calling setState will execute very fast, you have to call it hundreds of times to impact performance.

Upvotes: 6

Related Questions