componentWillMount() in ReactJS

componentWillMount() method is invoked just before component added to DOM. So after this method, component will mount to DOM.

componentWillMount() is the the method of mounting phase of component, So it is only called once.

Why componentWillMount() should be used?

componentWillMount() method is used to initialize state or props. So mostly, all that things you want to do before component is added to DOM can be done here.

Although you cna initialize state or props in constructor(). So it is debatable point what should be done in componentWillMount().

Points to remember while using componentWillMount()

There are many points that you should remember while using componentWillMount() method.

  • Do not add any side-effects task or subscription or server request in componentWillMount() method. You can use componentDidMount() lifecycle method.
  • Calling setState() method in componentWillMount() will not cause re-rendering. Because after componentWillMount(), component is eventually going to render.
  • Try setting state and props in constructor instead of componentWillMount() method.

Conclusion

In this section, we learned about componentWillMount() method and for what it can be used.
In the next section, you will learn about componentWillReceiveProps() method of ReactJS component.