ComponentDidMount with React Hooks

We will be using the useEffect hook in the functional component to achieve the same behavior of componentDidMount in the class components. You can also check my other blog posts where you can do componentDidUpdate and componentWillUnmount with hooks. Let’s go through an example of componentDidMount.

First, we will be importing useEffect hook from the react library.

import { useEffect } from 'react';

Then, we can define a sample functional component.

const App = () => {
  return (
    <div>
      <h1>Hello World</h1>
    </div>
  );
}

Now, we can add our useEffect hook inside the sample component.

useEffect(() => {
  console.log('Im inside useEffect hook')
}, [])

Here, useEffect hook has two parameters. The first parameter is a callback function in which we can add our logic or code to be executed. The second one decides the behaviour of the hook. Since we have added the second parameter as an empty array, it will act as componentDidMount in the class components.

Final Code
import React, { useEffect } from 'react';

const App = () => {

  useEffect(() => {
    console.log('heeey')
  }, [])

  return (
    <div>
      <h1>Hello World</h1>
    </div>
  );
}

export default App;

2 Comments on “ComponentDidMount with React Hooks”

Leave a Reply