Implementing componentDidUpdate in React Hooks

Last updated : Jul 30, 2023 12:00 AM

The componentDidUpdate() lifecycle method runs everytime the component state is updated. That includes the initial render of the component. Here is what the componentDidUpdate() looks like in a class component.

import { Component } from "react";

interface Props {}
interface State {
   color: string
}

export default class App extends Component{

   constructor(props: Props) {
      super(props)
      this.state = {color: "green"};
      this.changeColor = this.changeColor.bind(this)
   }

   componentDidUpdate() {
      console.log("Component Did Update")
   }

   changeColor() {
      this.setState((prevState) => {
         if(prevState.color === "green"){
            return {color: "blue"}
         }
         else{
            return {color: "green"}
         }
      })
   }
   render(){
      return <button 
         style={{color: this.state.color}} 
         onClick={this.changeColor}>
            Change Color
      </button>
   }
}

Whenever I click the Change Color button, I update the component state. That triggers the componentDidMount() lifecycle method. It is important to avoid any state updates inside the componentDidUpdate() method since it creates an infinite loop.

componentDidUpdate() {
   console.log("Component Did Update")
   this.setState({color: "yellow"})
}

In this situation, this.setState({color: "yellow"}) updates the component state which itself triggers a componentDidUpdate(). The cycle goes on.

componentDidMount() equivalent in React Js hooks

The equivalent React hook is the useEffect() hook without a dependency array. No dependency array is crucial since the dependency array makes the useEffect() hook execute once only when the component is first loaded.

import { useEffect, useState } from "react"

export const FunctionalComponent = () =>{

const [color, setColor] = useState("green")

   useEffect(() => {
      console.log("Component Did Update")
   })

   const changeColor = () => {
      setColor((prevColor) => {
         if(prevColor === "green"){
            return "blue"
         }
         else{
            return "green"
         }
      })
   }

   return(
      <button style={{color: color}} onClick={changeColor}>Change Color</button>
   )
}

If I run this component, I will see the console log output "useEffect" whenever I click the "Change Color" button. Further clicks on the "Change Color" would trigger the useEffect() hook because of the state updates.

Lance

By: Lance

Hi, I'm Lance Raney, a dedicated Fullstack Developer based in Oklahoma with over 15 years of exp

Read more...