useEffect
A React Hook that lets you perform side effects in function components, such as data fetching, subscriptions, or manually changing the DOM.
Overview
useEffect runs after every render by default, but you can control when it runs by providing a dependency array. It's the function component equivalent of lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount combined. useEffect is essential for handling side effects in React applications.
Example
javascriptimport { useState, useEffect } from 'react'; function UserProfile({ userId }) { const [user, setUser] = useState(null); // Runs after every render useEffect(() => { document.title = user ? user.name : 'Loading...'; }); // Runs only on mount (empty dependency array) useEffect(() => { console.log('Component mounted'); }, []); // Runs when userId changes useEffect(() => { fetch(`/api/users/${userId}`) .then(res => res.json()) .then(data => setUser(data)); }, [userId]); // Cleanup function useEffect(() => { const timer = setInterval(() => { console.log('Tick'); }, 1000); // Cleanup runs on unmount or before re-running effect return () => { clearInterval(timer); }; }, []); return <div>{user?.name}</div>; }
Key Points
- Runs after render (by default)
- Dependency array controls when it runs
- Empty array [] runs only on mount
- Return function for cleanup
- Can have multiple useEffects
Learn More
- Hooks - React Hooks overview
- useState - State hook
- Lifecycle - Component lifecycle
- React Docs: useEffect