useEffect
is a versatile Hook in React that allows you to manage side effects in various ways. Here's a breakdown of the different ways you can use it:
1. Running Effects After Every Render (No Dependency Array):
This is the simplest form of useEffect
.
The effect callback function will run after every render of the component.
Use this when you need to perform an action on every render, regardless of changes in props or state.
Example :
useEffect(() => {
console.log('Component rendered');
});
2. Running Effects Only Once (Empty Dependency Array):
By providing an empty dependency array ([]
), you tell React to run the effect only once after the initial render.
This is useful for actions that should only happen once, such as fetching data on component mount or setting up an initial subscription.
Example :
useEffect(() => {
fetchData(); // Fetch data on component mount
}, []);
3. Running Effects Only When Dependencies Change (Dependency Array):
This is the most common and powerful way to use useEffect
.
You provide a dependency array containing the values that the effect depends on (props or state).
The effect will only run when any of the values in the dependency array change.
This helps to optimize performance and prevent unnecessary re-renders.
Example :
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]); // Run effect only when 'count' changes
4. Cleaning Up Effects:
If your effect sets up a subscription, timer, or other resource that needs to be cleaned up, you can return a cleanup function from the effect callback.
The cleanup function will be called:
This helps to prevent memory leaks and other issues.
Example :
useEffect(() => {
const timerID = setInterval(() => {
console.log('Tick');
}, 1000);
return () => {
clearInterval(timerID); // Cleanup function
};
}, []);
5. Using Multiple useEffect
Hooks:
You can use multiple useEffect
hooks in a single component.
This allows you to separate different side effects and manage them independently.
This can improve code organization and readability.
Example :
useEffect(() => {
// Effect 1: Update document title
}, [count]);
useEffect(() => {
// Effect 2: Fetch data
}, []);
Key Considerations :
useEffect
hooks to separate different side effects.By understanding these different ways to use useEffect
, you can effectively manage side effects in your React components.