John John - 14 days ago 6
React JSX Question

Why do componentWillUpdate() and componentWillMount() not trigger render function when setState used in these methods?

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 ?

Thank you.

Answer

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.

setState() in 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 render() pass.

Actually, for preparing state object for our very first render(), a better way is to use the constructor() instead of calling setState in componentWillMount.

More reading:


setState() in componentWillUpdate()

Note that you cannot call this.setState() here. If you need to update state in response to a prop change, use componentWillReceiveProps() instead.

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.

More reading: