React Lifecycle Methods Explained

In this post, we'd discuss the lifecycle of a typical React Component.

Each component in React has several lifecycle methods that you can override to run code at particular times in the process. Lifecycle methods can be used in ES6 Class Components but not in functional components.

Lifecycle of A React Component

1. Mounting In the process of mounting a component, a component goes through four lifecycles methods in the following order: a. constructor() b. getDerivedStateFromProps() c. render() d. componentDidMount()

2. Updating

In the case where props or state of a component changes, a component goes through 5 stages in the following order: a. getDerivedStateFromProps() b. shouldComponentUpdate() c. render() d. getSnapshotBeforeUpdate e. componentDidUpdate()

3. Unmounting A component has only one lifecycle method in the unmounting stage. a. componentWillUnmount()

Lifecycle Methods Explained

  1. constructor(props): This method is called when the component is first initialized. ( This is where you can set initial state values and bind class methods)

  2. render(): This method is a lifecycle method that returns elements as an output of the component. This method must always be treated as a pure function(Meaning it must not modify the component state). It takes input as props and state and returns a new/modified element.

  3. componentDidMount() is called when the component gets mounted. Here, you can perform async requests to fetch data from an API server.

  4. shouldComponentUpdate(nextProps, nextState): This method gets called everytime a component updates due to state or prop changes. The component and all it's children will render or not depending on what is returned from this method.

  5. getSnapshotBeforeUpdate(prevProps, prevState): In certain cases, the component needs to get information from the DOM before it is potentially changed. This method allows us to do that.

  6. componentDidUpdate(prevProps, prevState, snapshot): This a lifecycle method that is invoked immediately after updating, but not for the initial render. You can use it as to perform DOM operations or to perform more asynchronous requests. If your component implements the getSnapshotBeforeUpdate() method, the value it returns will be received as the snapshot parameter.

7.componentWillUnmount() is called before you destroy your component. You can use this lifecycle method to perform any cleanup tasks.

componentDidCatch(error, info) was introduced in React 16 to enable catching of errors easily in components.

No Comments Yet