Sobes.tech
Middle

What are the lifecycle methods in React and how can they be emulated using useEffect?

sobes.tech AI

Answer from AI

In a React class component, there are several lifecycle methods, the main ones being:

  • componentDidMount — called after the component is mounted;
  • componentDidUpdate — called after the component updates;
  • componentWillUnmount — called before the component unmounts.

In functional components with the useEffect hook, these methods can be emulated as follows:

import React, { useEffect } from 'react';

function MyComponent(props) {
  // componentDidMount
  useEffect(() => {
    // code that runs once after mounting
    console.log('Mounted');
  }, []); // empty dependencies array

  // componentDidUpdate
  useEffect(() => {
    // code that runs on props or state change
    console.log('Updated');
  }); // no second argument — runs after every render

  // componentWillUnmount
  useEffect(() => {
    return () => {
      // cleanup code before unmounting
      console.log('Unmounted');
    };
  }, []);

  return <div>{props.value}</div>;
}

Thus, useEffect with an empty dependencies array emulates componentDidMount and componentWillUnmount (via the cleanup function), while useEffect without a second argument emulates componentDidUpdate.

What are the lifecycle methods in React and how can… - sobes.tech