MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
The useEffect Hook for Side Effects0%
Study Materials
React.js for BeginnersProgress 0%
1.1Why React and Single-Page Architecture1.2Setting Up Modern React with Vite1.3React Project Directory Structure and Entry Points1.4Virtual DOM and React Render Cycle Explained
8.1Rules of React Hooks8.2The useEffect Hook for Side Effects8.3The Dependency Array and Execution Lifecycle8.4Cleanup Functions in useEffect
HomeTutorialsReact.js for BeginnersThe useEffect Hook for Side Effects
The Dependency Array and Execution Lifecycle

The useEffect Hook for Side Effects

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

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.

1Render Phase:
2[Props & State] ──> [Pure JSX Calculation] ──> [DOM Painted to Screen]
3 │
4 ▼
5 Commit / Paint Complete!
6 │
7 ▼
8 [useEffect Fires Here]

2. Anatomy of useEffect

The useEffect hook accepts two arguments:

1useEffect(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

1import React, { useState, useEffect } from 'react';
2 
3export default function CoursePage({ courseTitle }) {
4 const [enrolledCount, setEnrolledCount] = useState(120);
5 
6 // Synchronize browser tab title whenever courseTitle or enrolledCount changes
7 useEffect(() => {
8 document.title = `${courseTitle} (${enrolledCount} Students) | MSK Institute`;
9 }, [courseTitle, enrolledCount]); // Dependencies
10 
11 return (
12 <div className="course-view">
13 <h1>{courseTitle}</h1>
14 <p>Active Students: {enrolledCount}</p>
15 <button onClick={() => setEnrolledCount(prev => prev + 1)}>
16 Enroll Student
17 </button>
18 </div>
19 );
20}

4. Fetching Data with useEffect

When fetching data on initial component mount:

1import React, { useState, useEffect } from 'react';
2 
3export default function StudentList() {
4 const [students, setStudents] = useState([]);
5 const [loading, setLoading] = useState(true);
6 
7 useEffect(() => {
8 // Declare async function INSIDE effect callback
9 async function loadData() {
10 try {
11 const res = await fetch('https://api.example.com/students');
12 const data = await res.json();
13 setStudents(data);
14 } catch (err) {
15 console.error('Fetch failed:', err);
16 } finally {
17 setLoading(false);
18 }
19 }
20 
21 loadData();
22 }, []); // Empty array = Run ONLY ONCE when component mounts
23 
24 if (loading) return <p>Loading directory...</p>;
25 
26 return (
27 <ul>
28 {students.map(s => <li key={s.id}>{s.name}</li>)}
29 </ul>
30 );
31}

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• Knowledge Check

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.

Related Lessons

Previous LessonNext Lesson
Rules of React HooksThe Dependency Array and Execution Lifecycle

Practice Quiz

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

Mentor-Led Practical Training

Master React.js for Beginners with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext