useEffect is a powerful React Hook that lets you perform "side effects" in function components. Side effects are anything that interacts with the outside world or needs to run after the render cycle. Common side effects include data fetching, manually changing the DOM, setting up subscriptions, timers, logging, and more.
The basic syntax is useEffect(setupFunction, optionalDependencyArray).
Here are a few practical examples:
1. Fetching Data on Component Mount
This is one of the most common uses. You want to load data from an API as soon as your component appears on the screen.
import React, { useState, useEffect } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
// This function runs after the initial render and every time `userId` changes.
// The dependency array `[userId]` means it will re-run if `userId` is different.
// If `userId` is constant, it runs only once on mount.
const fetchUser = async () => {
setLoading(true);
setError(null); // Clear previous errors
try {
const response = await fetch(`https://api.example.com/users/${userId}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
setUser(data);
} catch (e) {
setError(e);
} finally {
setLoading(false);
}
};
fetchUser();
// No cleanup needed here as data fetching doesn't usually create subscriptions or timers
// that need to be torn down on unmount.
}, [userId]); // Dependency array: re-run effect if userId changes
if (loading) return <div>Loading user profile...</div>;
if (error) return <div>Error: {error.message}</div>;
if (!user) return <div>No user found.</div>;
return (
<div>
<h2>{user.name}</h2>
<p>Email: {user.email}</p>
<p>Bio: {user.bio}</p>
</div>
);
}
// Example usage:
// <UserProfile userId="123" />
Explanation:
- The
useEffect hook is used to perform the data fetching.
- The empty array
[] as the second argument (dependency array) means this effect will only run once after the initial render (like componentDidMount in class components). If userId was truly static, we'd use [].
- However, if
userId is a prop that can change, we include it in the dependency array [userId] so the effect re-fetches data whenever userId changes.
async/await is used for asynchronous operations.
useState is used to manage the user data, loading state, and error state.
2. Setting Up and Cleaning Up Event Listeners
When you add global event listeners (like window.resize or document.mousemove), you must clean them up when the component unmounts to prevent memory leaks.
import React, { useState, useEffect } from 'react';
function WindowSizeTracker() {
const [windowWidth, setWindowWidth] = useState(window.innerWidth);
const [windowHeight, setWindowHeight] = useState(window.innerHeight);
useEffect(() => {
// Function to update state on resize
const handleResize = () => {
setWindowWidth(window.innerWidth);
setWindowHeight(window.innerHeight);
};
// Add event listener when component mounts
window.addEventListener('resize', handleResize);
// Return a cleanup function
return () => {
// Remove event listener when component unmounts
window.removeEventListener('resize', handleResize);
console.log('Cleanup: Window resize listener removed.');
};
}, []); // Empty dependency array: runs only once on mount, cleans up on unmount.
return (
<div>
<h3>Window Dimensions</h3>
<p>Width: {windowWidth}px</p>
<p>Height: {windowHeight}px</p>
</div>
);
}
// Example usage:
// <WindowSizeTracker /> (try resizing your browser window)
Explanation:
- The
useEffect runs once on mount due to the [] dependency array.
- Inside the effect, we add a
resize event listener to the window.
- The
return statement within useEffect provides a cleanup function. This function runs right before the component unmounts (or before the effect re-runs if dependencies change).
- Cleaning up the event listener prevents the
handleResize function from being called on a component that no longer exists in the DOM, avoiding errors and memory leaks.
3. Synchronizing State with Local Storage
You might want to save some user preference or a counter to localStorage so it persists across browser sessions.
import React, { useState, useEffect } from 'react';
function ThemeSwitcher() {
// Initialize state from localStorage, or default to 'light'
const [theme, setTheme] = useState(() => {
const savedTheme = localStorage.getItem('appTheme');
return savedTheme ? savedTheme : 'light';
});
useEffect(() => {
// This effect runs whenever the `theme` state changes.
localStorage.setItem('appTheme', theme);
document.body.style.backgroundColor = theme === 'dark' ? '#333' : '#f0f0f0';
document.body.style.color = theme === 'dark' ? '#f0f0f0' : '#333';
}, [theme]); // Dependency array: re-run effect if `theme` changes
const toggleTheme = () => {
setTheme(prevTheme => (prevTheme === 'light' ? 'dark' : 'light'));
};
return (
<div style={{ padding: '20px', textAlign: 'center' }}>
<h1>Current Theme: {theme}</h1>
<button onClick={toggleTheme}>Toggle Theme</button>
<p>This theme preference will be saved in your browser's local storage!</p>
</div>
);
}
// Example usage:
// <ThemeSwitcher /> (try toggling and then refreshing the page)
Explanation:
- The
useState initializer function is used to read the initial theme from localStorage once.
- The
useEffect hook watches the theme state. Whenever theme changes, the effect runs.
- Inside the effect,
localStorage.setItem saves the current theme value.
- This ensures that the
localStorage value is always in sync with the component's theme state.
4. Direct DOM Manipulation (e.g., Focusing an Input)
Sometimes, you need to directly interact with a DOM element after it has rendered.
import React, { useEffect, useRef } from 'react';
function FocusInput() {
const inputRef = useRef(null); // Create a ref to attach to the input element
useEffect(() => {
// This effect runs once after the component mounts.
// It's safe to access inputRef.current here because the component is mounted.
if (inputRef.current) {
inputRef.current.focus(); // Focus the input element
}
}, []); // Empty dependency array: runs only once on mount.
return (
<div>
<label htmlFor="autofocus-input">Enter your name:</label>
<input id="autofocus-input" ref={inputRef} type="text" />
<p>This input field should be automatically focused when the component loads.</p>
</div>
);
}
// Example usage:
// <FocusInput />
Explanation:
useRef is used to get a direct reference to the DOM input element.
useEffect with an empty dependency array [] ensures the effect runs only once after the component mounts.
- Inside the effect,
inputRef.current.focus() imperatively sets the focus on the input field. This is a classic example where direct DOM manipulation is necessary and useEffect is the correct place for it.
Key Takeaways for useEffect:
- Side Effects: It's for anything that reaches outside the component's render scope (network requests, browser APIs, timers, etc.).
- When it runs:
- By default, after every render (if no dependency array).
- With
[] (empty array), it runs only once after the initial render, and its cleanup runs on unmount.
- With
[dep1, dep2] (dependencies), it runs after the initial render and whenever any of the listed dependencies change.
- Cleanup: The optional return function from
useEffect is crucial for cleaning up resources (e.g., clearing timers, removing event listeners, cancelling subscriptions) to prevent memory leaks and unexpected behavior.
- Avoid Overuse: While powerful, don't use
useEffect for things that can be done purely during rendering (e.g., calculating derived state).