ReactEasy

What is useEffect?

useEffect(setup, dependencies?) lets a component synchronize with something outside React, such as a network connection, a browser API, a timer or a third-party widget. The setup runs after React commits and the browser paints; its returned cleanup runs before the effect re-runs and when the component unmounts.

When effects run

  • No dependency array: after every render.
  • []: once after mount (cleanup on unmount).
  • [a, b]: after mount and whenever a or b changes (compared with Object.is).

Good uses

  • Subscriptions: WebSockets, window or document listeners, IntersectionObserver.
  • Integrating non-React widgets (maps, charts, video players).
  • Fetching data in apps without a framework or data library (with cleanup to ignore stale responses).
  • Syncing to external systems: document.title, analytics on mount.

You might not need an effect

  • Derived data: compute during render instead of setting state in an effect.
  • Responding to user events: do the work in the event handler.
  • Resetting state on prop change: use a key.
  • Data fetching in frameworks: use loaders, Server Components, or TanStack Query/SWR. The React Compiler lint rule set-state-in-effect flags common misuse.

Non-reactive logic

React 19.2's useEffectEvent extracts logic that reads the latest props or state without making them dependencies, for example logging with the current theme when a connection opens.

Strict Mode

In development, effects mount, unmount and mount again to verify cleanups.

Code example

tsx
1import { useEffect, useEffectEvent, useState } from "react";
2
3export function ChatRoom({ roomId, theme }: { roomId: string; theme: "light" | "dark" }) {
4 const [messages, setMessages] = useState<string[]>([]);
5
6 // React 19.2: reads the latest theme without making it a dependency
7 const onConnected = useEffectEvent(() => {
8 console.log(`connected to ${roomId} with ${theme} theme`);
9 });
10
11 useEffect(() => {
12 const socket = new WebSocket(`wss://chat.example.com/rooms/${roomId}`);
13 socket.addEventListener("open", onConnected);
14 socket.addEventListener("message", (e) => setMessages((m) => [...m, String(e.data)]));
15
16 return () => socket.close(); // runs before reconnecting to a new room and on unmount
17 }, [roomId]); // re-sync only when the room changes, not when the theme changes
18
19 useEffect(() => {
20 document.title = `${messages.length} messages`;
21 }, [messages.length]);
22
23 return <ul>{messages.map((m, i) => <li key={i}>{m}</li>)}</ul>;
24}

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 set.

Open in study app