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 (like componentDidMount).
  • 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

tsx
1import React, { useState, useEffect } from 'react';
2
3export default function LiveDataTracker({ userId }) {
4 const [data, setData] = useState(null);
5 const [loading, setLoading] = useState(true);
6 const [windowWidth, setWindowWidth] = useState(0);
7
8 // Effect 1: Data Fetching (Runs when userId changes)
9 useEffect(() => {
10 let isMounted = true;
11 setLoading(true);
12
13 async function fetchUserData() {
14 try {
15 const response = await fetch(`/api/users/${userId}`);
16 const result = await response.json();
17
18 // Prevent state update if component unmounted while fetching
19 if (isMounted) {
20 setData(result);
21 setLoading(false);
22 }
23 } catch (error) {
24 console.error("Fetch failed", error);
25 }
26 }
27
28 fetchUserData();
29
30 // Cleanup: Abort fetch or ignore result if unmounted
31 return () => {
32 isMounted = false;
33 };
34 }, [userId]); // Dependency array
35
36 // Effect 2: Subscriptions (Runs once on mount)
37 useEffect(() => {
38 const handleResize = () => setWindowWidth(window.innerWidth);
39
40 // Setup
41 window.addEventListener('resize', handleResize);
42 handleResize(); // Initial measurement
43
44 // Cleanup
45 return () => window.removeEventListener('resize', handleResize);
46 }, []);
47
48 if (loading) return <div>Loading user data...</div>;
49
50 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.

Open in study app