React Fundamentals & Hooks • Module 3 • Lesson 4
The useEffect
hook is one of the most important hooks in React. It allows you to perform side effects in your functional components. Think of side effects as anything that affects something outside of the current function being executed, such as:
useEffect(() => {
// Side effect code
return () => {
// Cleanup code (optional)
};
}, [dependencies]);
The useEffect hook accepts two arguments:
The dependency array is a crucial part of useEffect. It determines when the effect should run:
import { useState, useEffect } from 'react';
function PageTitle() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
In this example, the document title will be updated whenever the count
state changes.
The function returned from useEffect is called the cleanup function. It runs before the component unmounts and before the effect runs again (if it has dependencies that change).
useEffect(() => {
const subscription = subscribeToData();
// Cleanup function
return () => {
subscription.unsubscribe();
};
}, []);
The cleanup function is important for preventing memory leaks by removing event listeners, canceling network requests, or cleaning up subscriptions.
useEffect(() => {
let isMounted = true;
const fetchData = async () => {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
if (isMounted) {
setData(data);
}
} catch (error) {
if (isMounted) {
setError(error);
}
} finally {
if (isMounted) {
setLoading(false);
}
}
};
fetchData();
return () => {
isMounted = false;
};
}, []);
useEffect(() => {
const handleResize = () => {
setWindowWidth(window.innerWidth);
};
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);