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
useEffecthook. - To simulate
componentDidMountwithuseEffect:- Import
useEffectfrom 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 touseEffect. This ensures the effect runs only once, similar tocomponentDidMount. - 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.
- Import
- The cleanup function returned from
useEffectis 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
useEffectthat 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
[], simulatingcomponentDidMount. - Inside the effect's callback function, we define an asynchronous function
fetchDatato perform the API call usingfetch. Once the data is fetched, we update the component's state with the fetched data usingsetData. - The component renders either a "Loading..." message while the data is being fetched or the fetched data once it's available.
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:
