Reputation: 31
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:
componentWillMount()
componentDidMount()
shouldComponentUpdate()
componentDidUpdate()
Upvotes: 0
Views: 1060
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.
Upvotes: 0
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