Implementing componentDidMount in React Hooks

Last updated : Jul 30, 2023 12:00 AM

The componentDidMount() lifecycle method equivalent in React hooks is the useEffect() hook with an empty dependency array. The componentDidMount() is executed right after the component is mounted and rendered. Here is an example of the componentDidMount() in a class component.

import { Component } from "react";

interface Props {}
interface State {
   color: string
}

export default class App extends Component<Props, State>{

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

   componentDidMount() {
      this.setState({color: "yellow"})
      console.log("componentDidMount")
   }

   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>
   }
}

If I run this component, I will see the console log output "componentDidMount" only once when the component is first mounted. Further clicks on the "Change Color" would not trigger the componentDidMount() lifecycle method because it is already mounted.

componentDidUpdate() equivalent in React Js hooks

The equivalent React hook is the useEffect() hook with an empty dependency array. The empty dependency array is crucial since it makes the useEffect() hook executes once only when the component is first loaded.

import { useEffect, useState } from "react"

export const FunctionalComponent = () =>{

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

   useEffect(() => {
      setColor("yellow")
      console.log("useEffect")
   },[])

   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" only once when the component is first mounted. Further clicks on the "Change Color" would not trigger the useEffect() hook because it is already mounted.

Lance

By: Lance

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

Read more...