We can call setState() inside every component lifecycle methods.
Why do we not call it inside componentWillUpdate() and componentWillMount() ?
Why don't these methods trigger render function when put setState inside those ?
Can anyone explain it in detail please ?
setState() in componentWillMount()
componentWillMount()is invoked immediately before mounting occurs. It is called before
render(), therefore setting state in this method will not trigger a re-rendering.
componentWillMount() will not trigger a re-render, but we have never called
render() at this point yet. So, setting state here will prepare the state object before we enter the first
Actually, for preparing state object for our very first
render(), a better way is to use the
constructor() instead of calling
setState() in componentWillUpdate()
Note that you cannot call
this.setState()here. If you need to update state in response to a prop change, use
componentWillUpdate() is called every time a re-render is required, such as when
this.setState() is called. The reason we do not call
this.setState() here is that the method triggers another
componentWillUpdate(). If we trigger a state change in
componentWillUpdate() we will end up in an infinite loop.