![]() |
VOOZH | about |
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.
useEffect hook.componentDidMount with useEffect:useEffect from the 'react' package.useEffect.useEffect. This function contains the code that should run after the component mounts.[] as the second argument to useEffect. This ensures the effect runs only once, similar to componentDidMount.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.
useEffect that fetches data from an API when the component mounts.[], simulating componentDidMount.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.Output: