ComponentDidUpdate with React Hooks

We can make use of the hook useEffect in order to achieve the same behavior of componentDidUpdate in the class components. useEffect hook receives a callback function that will execute when the component is mounted and whenever it updates. You can also check my other blog posts where you can do componentDidMount and componentWillUnmount with hooks. Let’s go through an example of componentDidUpdate.

First of all, we can create a functional component with name App.

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

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

  useEffect(() => {
    console.log('hey, Im inside useEffect Hook')
  })

This code inside the hook executes after every renders similar to componentDidUpdate. You can add all your code to be executed after each renders inside this useEffect hook.

Final Code

import React, { useEffect } from 'react';

const App = () => {

  useEffect(() => {
    console.log('hey, Im inside useEffect Hook')
  })

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

export default App;

Similar Posts

One Comment

Leave a Reply