skip to Main Content

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


  1. That depends on what you consider "not working".

    In class components, setState serves two purposes:

    1. Update this.state of the component
    2. Indicate to React that the components needs to re-render

    componentWillMount according to the docs (for the non-deprecated name UNSAFE_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 update this.state but it will not call the render method in addition to manipulating this.state. render will be called later for the initial render.

    Couple other notes from the docs:

    UNSAFE_componentWillMount is the only lifecycle method that runs during server rendering. For all practical purposes, it is identical to constructor, so you should use the constructor for this type of logic instead.

    Calling setState inside UNSAFE_componentWillMount in a class component to initialize state is equivalent to passing that state as the initial state to useState in a function component.

    … 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.

    Login or Signup to reply.
  2. Is it true that setState will not work in that lifecycle method at all?

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search