Open In App

How to simulate componentDidMount with useEffect?

Last Updated : 21 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Javascript




import React, {
    useState,
    useEffect
} from 'react';
 
function MyComponent() {
    const [data, setData] = useState(null);
 
    useEffect(() => {
 
        console.log('Component mounted');
        const fetchData = async () => {
            try {
                const response = await
                    fetch('https://fakestoreapi.com/products');
                const result = await response.json();
                setData(result);
            } catch (error) {
                console.error('Error fetching data:', error);
            }
        };
 
        // Call fetchData when the component mounts
        fetchData();
        return () => {
            console.log('Component unmounted');
        };
    }, []);
    /*
        Empty dependency array ensures the effect
        runs only once after initial mount
     */
 
    return (
        <div>
            {/* Display fetched data */}
            {
                data ? (<div>
                    <h1>Data fetched:</h1>
                    <pre>
                        {
                            JSON.stringify(data, null, 2)
                        }
                    </pre>
                </div>) :
                    (<div>Loading...</div>)
            }
        </div>
    );
}
 
export default MyComponent;


Output:

gfg39

Output



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads