DEV Community

Cobbygraves
Cobbygraves

Posted on • Edited on

Class Component Vs Functional Component(Lifecycle Methods)

Before we begin I want to say that this is a three part series tutorial

Part 1 - ComponentDidMount
Part 2 - ComponentDidUpdate
part 3 - ComponentWillUnmount

Let me begin by saying that prior to react 16.8 class based component were the defector standard to implement the lifecycle methods in a react component.
The lifecycle methods were as follows;

componentDidMount

componentDidUpdate

componentWillUmount

The componentDidMount method is called when the component is mounted to the DOM. The componentDidUpdate method is called anytime the component receives an update to any of it props or state. This update causes the component to re-render to display it current state of the UI. The componentWillUnmount is called when the react component is about to be removed from the DOM

React hooks were introduced in functional components which made it possible to implement the lifecycle methods in a react component using the useEffect hook.

Now, let look at how to implement the lifecycle methods in both functional and class based component.
Let consider the class based component and functional component respectively.

class based componentclass based component

function based componentfunctional based component

To implement componentDidMount in a class based component let consider the code snippet below:

componentDidMount

To implement the same code in a functional component let consider the code snippet below:

componentDidMount

Let discuss the two code snippet above and see how the componentDidMount lifecycle method was implemented in each of them.

If we look at the class based component, the componentDidMount method was just defined inside the class based component to implement it. On the other hand if we look at the function based component the useEffect hook was used to implement the componentDidMount. Remember that the useEffect hook takes an optional array of dependencies. In the functional component the array of dependencies was left empty.

The useEffect hook can be configured to have different effect in a functional component.

NB: Whenever the useEffect hook is configured to have an empty array of dependencies, it is equivalent to the componentDidMount function in a class based component.

I hope you found value in this tutorial on the first part of the series of the lifecycle methods in react components. Please don't forget to read the other two part of the tutorial for a better understanding of this concept.

Top comments (0)