Sure, componentWillMount is not something talk about now due to it being obsolete but I came across the react docs and it says that
componentWillMount is called before render which means setting state
synchronously in componentWillMount will not cause extra render call.
Is it true that setState will not work in that lifecycle method at all?
2
Answers
That depends on what you consider "not working".
In class components,
setState
serves two purposes:this.state
of the componentcomponentWillMount
according to the docs (for the non-deprecated nameUNSAFE_componentWillMount
) "will [be called] immediately after the constructor." which also means it is called before your component is ever rendered initially.You can technically use
setState
within the function to updatethis.state
but it will not call therender
method in addition to manipulatingthis.state
.render
will be called later for the initial render.Couple other notes from the docs:
… which is pretty much equivalent to defining the initial state as field in the class component or setting
this.state
in the constructor.Especially that last quote seems to indicate that it will update
this.state
.So back to your question: "Is it true that setState will not work in that lifecycle method at all?" If "working" means "setting the state of the component", it will do that. If "working" means "causes the
render
function to be called again", the answer is no (because it doesn’t make sense to do that before the initial render.That’s incorrect. That comment is pointing out that if you synchronously set state during
componentWillMount
, then the very first render of the component will be able to include those state changes. As such, react doesn’t need to do an extra render, because the normal first render is sufficient.So the page will render with the state you set. It just does that in one render, not two.