Skip to main content
⚑ OpenDevDocs
React
frontendreactGuideIntermediate

The useEffect Hook in React

Mastering useEffect: synchronizing with external systems, cleanup functions, dependency array rules, and avoiding unnecessary effects.

Verified: 2026-09-30
Tested on:react 19.x
Platforms:
web
#react#hooks#use-effect#lifecycle#cleanup

The useEffect Hook in React

The useEffect hook lets you synchronize a component with external systems (such as browser APIs, network subscriptions, document titles, or timers).


1. Syntax and Anatomy

import { useEffect } from "react";

useEffect(() => {
  // 1. Setup code (runs after DOM renders)
  const connection = createChatConnection(roomId);
  connection.connect();

  // 2. Cleanup function (runs before next effect and on component unmount)
  return () => {
    connection.disconnect();
  };
}, [roomId]); // 3. Dependency array

2. Dependency Array Rules

Dependency OptionExecution Timing
Omitted useEffect(fn)Runs after every single render (rarely desired).
Empty Array []Runs once on mount, cleans up on unmount.
With Dependencies [dep1, dep2]Runs on mount and whenever dep1 or dep2 changes identity (Object.is).

3. When NOT to Use useEffect

❌ Anti-Pattern: Syncing state with props in an effect

// ❌ Redundant effect causes unnecessary extra re-render
useEffect(() => {
  setFullName(`${firstName} ${lastName}`);
}, [firstName, lastName]);

// βœ… Correct: Calculate directly during render!
const fullName = `${firstName} ${lastName}`;

On this page