What is useEffect and what are its common use cases?
useEffect is the mechanism for handling side effects in functional components. A "side effect" is any operation that affects something outside the scope of the function being executed, such as data fetching, manual DOM manipulation, or setting up subscriptions.
The Dependency Array:
The second argument to useEffect controls when the effect runs:
- No array: Runs after EVERY render.
- Empty array
[]: Runs exactly ONCE after the initial render (likecomponentDidMount). - Array with variables
[var1, var2]: Runs on initial render AND whenever any variable in the array changes between renders.
The Cleanup Function:
Effects can optionally return a cleanup function. React runs this cleanup function before the component unmounts, and before re-running the effect on subsequent renders. This is crucial for preventing memory leaks (e.g., removing event listeners, clearing intervals, or aborting fetch requests).
Code example
1import React, { useState, useEffect } from 'react';23export default function LiveDataTracker({ userId }) {4 const [data, setData] = useState(null);5 const [loading, setLoading] = useState(true);6 const [windowWidth, setWindowWidth] = useState(0);78 // Effect 1: Data Fetching (Runs when userId changes)9 useEffect(() => {10 let isMounted = true;11 setLoading(true);1213 async function fetchUserData() {14 try {15 const response = await fetch(`/api/users/${userId}`);16 const result = await response.json();1718 // Prevent state update if component unmounted while fetching19 if (isMounted) {20 setData(result);21 setLoading(false);22 }23 } catch (error) {24 console.error("Fetch failed", error);25 }26 }2728 fetchUserData();2930 // Cleanup: Abort fetch or ignore result if unmounted31 return () => {32 isMounted = false;33 };34 }, [userId]); // Dependency array3536 // Effect 2: Subscriptions (Runs once on mount)37 useEffect(() => {38 const handleResize = () => setWindowWidth(window.innerWidth);3940 // Setup41 window.addEventListener('resize', handleResize);42 handleResize(); // Initial measurement4344 // Cleanup45 return () => window.removeEventListener('resize', handleResize);46 }, []);4748 if (loading) return <div>Loading user data...</div>;4950 return (51 <div>52 <h3>User Data: {JSON.stringify(data)}</h3>53 <p>Current window width: {windowWidth}px</p>54 </div>55 );56}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React Hooks set.