Open In App

How to simulate componentDidMount with useEffect?

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:

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






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:

Output




Article Tags :