Effect Dependencies and Cleanup
Learn how dependency arrays control when Effects run and how cleanup functions remove event listeners, clear timers, and release resources when they are no longer needed.
1. What Are Effect Dependencies?
Effect dependencies are values listed in the dependency array of the useEffect Hook. React compares these values between renders to determine whether an Effect needs to run again.
Dependencies may include state variables, props, and other reactive values used by the Effect.
2. Types of Dependency Arrays
Without a Dependency Array
useEffect(() => {
console.log("Effect executed");
});
The Effect runs after every committed render.
With an Empty Dependency Array
useEffect(() => {
console.log("Initial Effect");
}, []);
The Effect runs after the initial commit. In development Strict Mode, React may run an additional setup and cleanup cycle.
With a Dependency
useEffect(() => {
console.log("Count:", count);
}, [count]);
The Effect runs after the initial commit and again whenever the value of count changes.
3. How Dependencies Work
React checks the dependency values after rendering. If a dependency changes, React runs the previous cleanup, when provided, and then executes the Effect again.
4. Example: useEffect with Dependencies
This example updates the browser tab title whenever the counter value changes.
Example Code
import { useEffect, useState } from "react";
function App() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
return (
<div>
<h2>Counter Application</h2>
<p>Count: {count}</p>
<button onClick={() =>
setCount(previousCount =>
previousCount + 1
)
}>
Increase
</button>
</div>
);
}
export default App;
Expected Output
Counter Application
Initially: Count: 0
After one click: Count: 1
After two clicks: Count: 2
The browser tab title changes to match the current count.
5. What Is Effect Cleanup?
Cleanup is a function returned by useEffect. It reverses or removes the work performed by the Effect setup when that work is no longer needed.
Cleanup is useful for:
- Removing event listeners.
- Clearing timers and intervals.
- Unsubscribing from external services.
- Aborting or ignoring outdated asynchronous requests.
6. Example: Event Listener Cleanup
This example registers a window resize event listener and removes it during cleanup.
Example Code
import { useEffect } from "react";
function App() {
useEffect(() => {
function handleResize() {
console.log(
"Window width:",
window.innerWidth
);
}
window.addEventListener(
"resize",
handleResize
);
return () => {
window.removeEventListener(
"resize",
handleResize
);
};
}, []);
return (
<div>
<h2>Window Resize Example</h2>
<p>Resize the browser window and
check the console.</p>
</div>
);
}
export default App;
Expected Output
Window Resize Example
Resize the browser window and open the console.
Example console message:
Window width: 1200The number depends on the actual browser window width.
7. Example: Clearing an Interval
An interval continues running until it is cleared. We can return a cleanup function to clear the interval when the component is removed.
Example Code
import { useEffect } from "react";
function App() {
useEffect(() => {
const timerId = setInterval(() => {
console.log("Timer running");
}, 1000);
return () => {
clearInterval(timerId);
};
}, []);
return (
<div>
<h2>Timer Example</h2>
<p>Check the browser console.</p>
</div>
);
}
export default App;
Expected Output
Timer Example
Timer running
Timer running
Timer running
The message is logged approximately every second while the Effect is active.
8. Important Points
- Include all reactive values used by an Effect in its dependency array.
- An omitted dependency array causes the Effect to run after every committed render.
- An empty dependency array means the Effect does not re-run because of changing reactive dependencies.
- Cleanup runs before an Effect re-runs and when the component is removed.
- Use clearInterval to stop an interval and removeEventListener to remove an event listener.
- Avoid unnecessary Effects for values that can be calculated directly during rendering.
9. Practice Tasks
Complete the following exercises:
- Create an Effect that logs a message after every committed render.
- Create an Effect that updates the browser tab title when a counter changes.
- Compare an empty dependency array with an omitted dependency array.
- Register a window resize listener and remove it using cleanup.
- Create an interval that logs a message every second and clears the interval during cleanup.
- Explain when React runs an Effect cleanup function.