Keshav Jha
Keshav Jha

Reputation: 31

In which reactjs lifecycle method we should not write the code to update state?

I am trying to understand the react JS lifecycle methods and came across a question that in which of the following methods we are not suppose to call setState() functionality to update the component:

Upvotes: 0

Views: 1060

Answers (2)

keul
keul

Reputation: 7819

In general: try to keep setState usage for user interactions like event handlers.

componentWillMount: this was good point where to call setState, but this method is deprecated so try to stop using it. Use the class constructor instead.

componentDidUpdate: you can call setState here but it will trigger a new render (and so another call to componentDidUpdate itself). If you really want, you will commonly call setState here behind some sort of condition.

componentDidMount: same as above, you will trigger a new render immediately after the mount so this is not encouraged for performance reason. A good exception: fetch/AJAX actions perform here.

shouldComponentUpdate: no, keep this method only for evaluating if you must perform a re-render or not. In general: do not use side-effects like setState here.

Keep in mind you have available the getDerivedStateFromProps static method if you need to eval a state based on props (this commonly cover any usage of setState inside didMount/didUpdate).

Most of the time a new key prop on a component will remove the needs of other complex setState usage around your code.

See https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key

Upvotes: 0

Sultan H.
Sultan H.

Reputation: 2938

componentWillMount() Basically, this will be invoked before render(), thus, it will never trigger a re-render, so you need to avoid using setState() in it.

Further, componentDidMount() is originally the WHERE you are going to make AJAX requests, else, it's totally ok to use the setState in the life cycle methods you asked for.

Ref to read: React Lifecycle Methods- how and when to use them

Upvotes: 1

Related Questions