Menu

React useEffect: Side Effects, Dependencies & Cleanup

useEffect Running Side Effects

What is useEffect?

A side effect is anything a component does beyond calculating and returning JSX: fetching data, setting a timer, updating the page title, subscribing to an event.

useEffect runs such code after the component renders.

Why is it Used?

You cannot put a fetch() call directly in the component body. It would run on every single render, and each response would trigger another render, creating an infinite loop. useEffect gives you control over when that code runs.

Syntax

jsx

useEffect(() => {
  // effect code
}, [dependencies]);

The second argument the dependency array is what controls the timing.

Dependency array

When the effect runs

[] (empty)Once, after the first render
[value]After the first render, and whenever value changes
Omitted entirelyAfter every render usually a mistake

Example

src/components/CourseTimer.jsx

jsx

import { useState, useEffect } from "react";

function CourseTimer({ courseName }) {
  const [seconds, setSeconds] = useState(0);

  // Runs once when the component first appears
  useEffect(() => {
    const intervalId = setInterval(() => {
      setSeconds(prev => prev + 1);
    }, 1000);

    // Cleanup — runs when the component is removed
    return () => clearInterval(intervalId);
  }, []);

  // Runs whenever courseName changes
  useEffect(() => {
    document.title = `Studying: ${courseName}`;
  }, [courseName]);

  return <p>Time spent: {seconds} seconds</p>;
}

export default CourseTimer;

How It Works

  • The first effect has [], so the timer is created once, not on every render.
  • setSeconds(prev => prev + 1) uses the functional form, so the effect does not need seconds as a dependency.
  • The return () => clearInterval(intervalId); is the cleanup function. React runs it when the component is removed from the screen, or before re-running the effect. Without it, the timer would keep running after the component disappears — a memory leak.
  • The second effect depends on courseName, so it re-runs only when that prop changes.

Output

The number of seconds increases every second, and the browser tab title shows the current course name.

The Double-Run in Development

In development, React's StrictMode runs every effect twice on mount, on purpose. It is checking that your cleanup function works correctly. This does not happen in the production build. If your effect breaks when run twice, it has a missing or incorrect cleanup.


ReactJS Tutorial

VA

Vishalini A



Learn via Video Course

React.js for Beginners: Build Modern Web Applications with React Logo

React.js for Beginners: Build Modern Web Applications with React

6 hrs



Get in Touch For Details