In React, the useEffect
hook simplifies managing side effects in functional components. It lets you get data, subscribe, or modify the DOM in your components. The hook uses a function that runs after the component shows up.
The useEffect
hook has two main parts: the "start" part and the "stop" part.
Mounting Phase:
When a component is first displayed and added to the DOM, the
useEffect
hook is used during the mounting phase.The code inside the
useEffect
callback runs after the component's initial appearance.This phase is typically for tasks that should happen only once when the component is first shown, such as fetching data, setting up subscriptions, or starting state.
Example:
useEffect(() => {
// Code here runs after the component is initially mounted
console.log('Component is mounted');
// Cleanup function (optional)
return () => {
console.log('Component will unmount (cleanup)');
// Perform cleanup tasks, unsubscribe from subscriptions, etc.
};
}, []); // Empty dependency array means this effect runs once after the initial render
Unmounting Phase:
When a component is about to be taken out of the DOM (unmounted), the
useEffect
hook can return a cleanup function if needed.The cleanup function runs before the component is unmounted, allowing you to clean up resources or do any required cleanup tasks.
This helps avoid memory leaks and makes sure resources are properly released when the component isn't needed anymore.
Example:
useEffect(() => {
// Code here runs after the component is initially mounted
// Cleanup function
return () => {
// Code here runs before the component is unmounted
console.log('Component will unmount (cleanup)');
// Perform cleanup tasks, unsubscribe from subscriptions, etc.
};
}, []); // Empty dependency array means this effect runs once after the initial render
In the examples above, we make a cleanup function by returning a function from the useEffect
callback. This cleanup function works when the component is about to be removed. It's useful for tasks like stopping subscriptions or releasing resources to avoid memory leaks. The empty dependency array ([]
) ensures the effect and cleanup functions run just once after the first render. If there are dependencies in the array, the effect and cleanup will run when those dependencies change.