Ayush Mishra
Ayush Mishra

Reputation: 267

Calling setState inside componentDidMount synchronously

I am beginner in react and I am learning about lifecycle hooks. I came across some articles stating don't call setState synchronously inside componentDidMount. But we can setState in then block of promise.

The reason mentioned was setState will cause re-render of the component, which will affect performance.

My question is, even if I write setState inside then block of promise, re-render will be there anyways, also setState is asynchronous so it won't be called immediately. So why its not recommended to call setState inside componentDidMount synchronously, And how does writing inside then block of promise solves the problem if there are any.

PS: I have researching on SO for quite a while, but couldn't find answers that says don't call setState synchronously, I found some related answers, but didn't answer my question, and I couldn't get them because they were totally related to some scenario.

Upvotes: 2

Views: 763

Answers (1)

dev mamba
dev mamba

Reputation: 784

React setState calls are asynchronous. React decides when to do it efficiently. For example, multiple setState calls are batched together into one single update. The way to get around this is using setStates's 2nd parameter which is a callback that will execute once setState is completed and the component re-rendered.

handleThis = () => {
    this.setState({someVar: someVal}, funcToCallimmediately )
}

To test, console.log the state variable just after setState() and write another console.log inside the "funcToCallimmediately" function.

📝 Take note that if you need to set the state based on the previous state you should use another method. First, just know that setState's 1st parameter can be an object and can also be a function. So you do it like this...

this.setState((state, props) => {
  return {counter: state.counter + props.step};
});

To understand more, read more about setState() here. You'll get what you need.

Upvotes: 1

Related Questions