The useEffect Hook for Side Effects0%

The useEffect Hook for Side Effects

Beginner12 min read•Updated: Jul 11, 2026
Study MaterialsCheatsheet

The useEffect Hook for Side Effects

1. What Are Side Effects?

A React component's primary job during rendering is pure: calculating the Virtual DOM representation for a given set of props and state.

However, modern applications frequently need to perform operations that reach outside the component's render scope:

  • Fetching data from an external REST API
  • Setting up a WebSocket connection or event subscription
  • Manually interacting with browser APIs (e.g., modifying document.title or reading geolocation)
  • Setting timers (setTimeout, setInterval)
  • Recording analytics page views

These operations are known as Side Effects (or simply "effects"). In React functional components, side effects are managed using the useEffect hook.

Output
Render Phase:
[Props & State] ──> [Pure JSX Calculation] ──> [DOM Painted to Screen]
│
▼
Commit / Paint Complete!
│
▼
[useEffect Fires Here]

2. Anatomy of useEffect

The useEffect hook accepts two arguments:

JSX
useEffect(setupFunction, dependencyArray);
  1. 1
    The Setup Function: The callback containing the side effect code. React executes this function after the browser has painted the DOM.
  2. 2
    The Dependency Array (Optional): An array of variables that dictates when the effect should re-run.

3. Basic Example: Synchronizing Document Title

JSX
import React, { useState, useEffect } from 'react';
 
export default function CoursePage({ courseTitle }) {
const [enrolledCount, setEnrolledCount] = useState(120);
 
// Synchronize browser tab title whenever courseTitle or enrolledCount changes
useEffect(() => {
document.title = `${courseTitle} (${enrolledCount} Students) | MSK Institute`;
}, [courseTitle, enrolledCount]); // Dependencies
 
return (
<div className="course-view">
<h1>{courseTitle}</h1>
<p>Active Students: {enrolledCount}</p>
<button onClick={() => setEnrolledCount(prev => prev + 1)}>
Enroll Student
</button>
</div>
);
}

4. Fetching Data with useEffect

When fetching data on initial component mount:

JSX
import React, { useState, useEffect } from 'react';
 
export default function StudentList() {
const [students, setStudents] = useState([]);
const [loading, setLoading] = useState(true);
 
useEffect(() => {
// Declare async function INSIDE effect callback
async function loadData() {
try {
const res = await fetch('https://api.example.com/students');
const data = await res.json();
setStudents(data);
} catch (err) {
console.error('Fetch failed:', err);
} finally {
setLoading(false);
}
}
 
loadData();
}, []); // Empty array = Run ONLY ONCE when component mounts
 
if (loading) return <p>Loading directory...</p>;
 
return (
<ul>
{students.map(s => <li key={s.id}>{s.name}</li>)}
</ul>
);
}

Note: The callback function passed to useEffect cannot be marked async directly (e.g. useEffect(async () => ...) is forbidden) because an async function returns a Promise, whereas React expects useEffect to return either a cleanup function or nothing!


Interactive Quiz

Practice Quiz

Question 1
What is a "side effect" in the context of React development?
Question 2
When does the useEffect callback function execute relative to the browser painting the screen?
Question 3
Why is it invalid to write useEffect(async () => { ... }, [])?
Question 4
What does an empty dependency array [] signify to useEffect?
Question 5
Where should side effects like network requests or subscriptions NOT be performed in a React component?
Next Lesson

The Dependency Array and Execution Lifecycle

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

PrevNext