VOOZH about

URL: https://www.geeksforgeeks.org/reactjs/how-to-simulate-componentdidmount-with-useeffect/

⇱ How to simulate componentDidMount with useEffect? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to simulate componentDidMount with useEffect?

Last Updated : 27 Jul, 2025

componentDidMount is a lifecycle method that runs after a component has been mounted or rendered to the DOM. It's often used for tasks like fetching data from an API or setting up event listeners.

Simulating componentDidMount with useEffect:

  • In functional components, you can achieve similar behavior using the useEffect hook.
  • To simulate componentDidMount with useEffect:
    • Import useEffect from the 'react' package.
    • Inside your functional component, call useEffect.
    • Pass a function as the first argument to useEffect. This function contains the code that should run after the component mounts.
    • Pass an empty dependency array [] as the second argument to useEffect. This ensures the effect runs only once, similar to componentDidMount.
    • Inside the effect function, perform any necessary actions, like fetching data from an API or setting up event listeners.
    • Optionally, return a cleanup function from the effect if you need to perform cleanup tasks when the component unmounts.
  • The cleanup function returned from useEffect is called when the component unmounts, allowing you to clean up resources like event listeners to prevent memory leaks.

Example: Below is an example of simulating componentDidMount with useEffect.

  • We define an effect using useEffect that fetches data from an API when the component mounts.
  • The effect runs only once after the initial mount because we provide an empty dependency array [], simulating componentDidMount.
  • Inside the effect's callback function, we define an asynchronous function fetchData to perform the API call using fetch. Once the data is fetched, we update the component's state with the fetched data using setData.
  • The component renders either a "Loading..." message while the data is being fetched or the fetched data once it's available.

Output:

👁 gfg39
Output


Comment