Question - Explain the lifecycle methods of React components in detail.
Answer -
The important React lifecycle methods are:
- getInitialState(): It is used to specify the default value of this.state. It is executed before the creation of the component.
- componentWillMount(): It is executed before a component gets rendered into the DOM.
- componentDidMount(): It is executed when the component gets rendered and placed on the DOM. Now, you can do any DOM querying operations.
- componentWillReceiveProps(): It is invoked when a component receives new props from the parent class and before another render is called. If you want to update the State in response to prop changes, you should compare this.props and nextProps to perform State transition by using this.setState() method.
- shouldComponentUpdate(): It is invoked when a component decides any changes/updation to the DOM and returns true or false value based on certain conditions. If this method returns true, the component will update. Otherwise, the component will skip the updating.
- componentWillUpdate(): It is invoked before rendering takes place in the DOM. Here, you can't change the component State by invoking this.setState() method. It will not be called, if shouldComponentUpdate() returns false.
- componentDidUpdate(): It is invoked immediately after rendering takes place. In this method, you can put any code inside this which you want to execute once the updating occurs.
- componentWillUnmount(): It is invoked immediately before a component is destroyed and unmounted permanently. It is used to clear up the memory spaces such as invalidating timers, event listener, canceling network requests, or cleaning up DOM elements. If a component instance is unmounted, you cannot mount it again.