2

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.

Ayush Mishra
  • 267
  • 3
  • 14
  • 1
    Additional rerenders are not bad. The problem are unnecessary rerenders. – Sulthan Feb 13 '21 at 07:38
  • @Sulthan, could you please explain a little more? I mean how setState outside of then block causes unnecessary re-renders? – Ayush Mishra Feb 13 '21 at 07:44
  • 2
    There is nothing wrong about calling setState in componentDidMount , the confusion might be coming from the warning in the official documentation that the component will re-render, but as you said yourself, if you change state the component will eventually re-render. https://reactjs.org/docs/react-component.html#componentdidmount – Nadia Chibrikova Feb 13 '21 at 08:52

1 Answers1

1

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.

dev mamba
  • 676
  • 7
  • 10