Effects: sync, then clean up

React chapter 139 · useEffect · dependencies · cleanup · StrictMode · source: react.dev/learn/synchronizing-with-effects

The problem

A chat room connects inside useEffect with no dependency array and no cleanup. Every keystroke re-renders the component, every render runs the effect, and connections pile up — even to rooms you already left.

The pattern that fixes it

Describe one synchronization: useEffect(() => { const c = connect(room); return () => c.disconnect(); }, [room]). React runs it after paint, skips it while room is unchanged, and always cleans up the old room before connecting to the new one.

In plain words

An effect keeps something outside React — a socket, a timer, a subscription — in step with your props and state. The cleanup function is the “undo” React calls before the next run and when the component goes away.

Checking into a hotel room: when you move rooms, you check out of the old one first. The cleanup is the check-out.

Terms

effect
Code React runs after the screen has updated, to sync with something outside React.
dependencies
The values the effect reads. React re-runs it only when one of them changed (Object.is).
cleanup
The function your effect returns. React calls it before re-running the effect and on unmount.

Going deeper

The exact order

Render → commit → (layout effects) → paint → cleanup of the previous effect → the new effect. Cleanup of the old run always happens before the new run, and it sees the old props — which is exactly what you need to disconnect from the old room.

Why StrictMode runs it twice

In development React mounts, unmounts and mounts again. If your effect leaks without cleanup, you see two connections immediately instead of in production a week later. It is a test, not a bug; the fix is a correct cleanup, never removing StrictMode.

You might not need an effect

Deriving data from props (filtering, totals) belongs in render. Reacting to a click belongs in the event handler. Effects are for synchronizing with external systems: network, timers, subscriptions, non-React widgets. Fetching in effects also needs race handling (chapter 98).

Keep learning

Overview

type here — every key is a render type here — the effect will not re-run Close chat (unmount) Open chat (mount) Clear log Chat is unmounted. Effect log, newest first (no effects yet) Real life: a chat room, a WebSocket price feed, a map widget — anything you open and must close.

Every render opens one more connection.

Type a few letters, switch rooms: the open-connections counter only grows, and old rooms stay connected. Type five letters in the message box. Count the connects in the log. Switch to #travel. You are now in two rooms at once. Close the chat. Nothing disconnects — the leak outlives the component. Effect lifecycle: mount, re-render, dependency change, unmount ↻ connect(general) type a message [room] unchanged → effect skipped room → travel ✕ disconnect(general) ↻ connect(travel) ✕ disconnect(travel) R render · C commit · P paint — effects always run after paint dev StrictMode: connect → disconnect → connect on mount, to test your cleanup An effect’s life Mount: React renders, commits and the browser paints. Then the effect runs: connect('general'). You type: the component re-renders, but room is unchanged, so React skips the effect. room becomes “travel”. After the new paint, React first runs the old cleanup: disconnect('general')… …then the effect again with the new value: connect('travel'). There is always exactly one connection. Unmount: the last cleanup runs. Nothing leaks. In development, StrictMode runs mount → cleanup → mount once on purpose. If you see two connections there, your cleanup is missing. undo, before the next run and on unmount

Exactly one open connection, whatever you do.

Type, switch rooms, close the chat. The log always pairs each connect with a disconnect.

More courses

  • Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
  • Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
  • Databases in depth — How a query becomes work. Indexes, isolation, locks, and the plans that explain why a page is slow — not an ORM tour.
  • System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
  • NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
  • Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
  • Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
  • AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
  • Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
  • TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
  • CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
  • Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
  • Docker — What an image is, why layers cache, and how containers find each other on a network.
  • Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
  • Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
  • AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
  • Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.