componentWillMount vs componentDidMount | React most asked question

Although componentWillMount is deprecated and if you are running with React 17 or above then you should prefix UNSAFE_ before componentWillMount life cycle method but difference between these two life cycle methods is one of the most asked questions in the interviews and also developer mostly gets confused when they try to see the answers of this questions on different forums online.
But the explanation is very simple and if you read this article fully then you will never get confused for it in future.
Lets see-
Difference #1
componentWillMount
This method gets called only once before component is rendered. So this lifecycle hook might cause issues if we try to do any DOM based operations. Because when this method is called at that time DOM is not created.
componentDidMount
This method gets called only once after first initial render of the component. So this lifecycle hook is the best place to perform any DOM based operations because before this method is called, DOM is already created.
Example (componentWillMount)

Above code will print Component Instance:: null because this method calls before render so DOM was not available when this method was called.
Example (componentDidMount)

Above code will print Component Instance :: <Comp-Instance> because DOM was already created when this method was called.
Difference #2
componentWillMount
setState() method call inside this life cycle hook doesn’t cause component re-rendering because component is not rendered once when this method is called.
componentDidMount
setState() method call inside this life cycle hook causes component re-rendering because component is already rendered once before this method is called.
Example (componentWillMount)

Above code will print “Rendering — “ message only once because calling setState() from componentWillMount() won’t cause re-rendering.
Example (componentDidMount)

Above code will print “Rendering — “ twice because calling setState() method from componentDidMount causes re-rendering.
I hope this article will help you to never confused now between these two life cycle looks.
Stay tuned and subscribe my medium channel!!!