Synchronizing with effects

Topic 2 of 5 in Refs & effects8 min readIntermediateFree course

Overview

Rendering must be pure, and event handlers handle user actions. But some code needs to run simply because a component is on the screen: connecting to a chat server, subscribing to the browser’s online/offline events, syncing a value to localStorage, or controlling a map widget. These are effects: they synchronise your component with a system outside React.

Your first effect

JSX
import { useEffect, useState } from 'react';

function OnlineIndicator() {
  const [isOnline, setIsOnline] = useState(navigator.onLine);

  useEffect(() => {
    function handleOnline() { setIsOnline(true); }
    function handleOffline() { setIsOnline(false); }

    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);

    return () => {
      window.removeEventListener('online', handleOnline);
      window.removeEventListener('offline', handleOffline);
    };
  }, []);

  return <span>{isOnline ? '🟢 Online' : '🔴 Offline'}</span>;
}

useEffect takes two arguments:

  1. A setup function containing the code to synchronise. It may return a cleanup function that undoes what setup did.
  2. A dependency array listing the values the effect depends on.

React runs the setup after the component has rendered and the DOM has been updated — effects never block the screen from painting.

The lifecycle of an effect

An effect does two things: start synchronising (setup) and stop synchronising (cleanup). React runs them at the right times:

JSX
function ChatRoom({ roomId }) {
  useEffect(() => {
    const connection = createConnection(roomId);
    connection.connect();
    return () => connection.disconnect();
  }, [roomId]);

  return <h1>Welcome to #{roomId}</h1>;
}

The effect connects to the room and returns a cleanup that disconnects. On mount with roomId “general” it connects to general. When roomId changes to “music” it disconnects from general and connects to music. A re-render with the same roomId does nothing. On unmount it disconnects from music.

  1. Mount: the component appears → setup runs → connect to general.
  2. Dependencies change: roomId becomes music → cleanup runs with the old values (disconnect general), then setup runs with the new ones (connect music).
  3. Re-render with same dependencies: nothing happens.
  4. Unmount: the component disappears → cleanup runs (disconnect music).

Think of each effect as describing how to start and stop syncing with one thing, not as “code that runs on mount”.

Dependencies

The dependency array tells React when to re-synchronise:

Dependencies When the effect re-runs
[roomId, serverUrl] after the first render, and whenever either value changes
[] only after the first render (and cleanup on unmount)
(no array) after every render — rarely what you want

Every reactive value the effect reads must be listed. Reactive values are props, state, and anything calculated from them inside the component. React compares each dependency with its previous value using Object.is.

JSX
function ChatRoom({ roomId }) {
  const [serverUrl, setServerUrl] = useState('https://chat.example');

  useEffect(() => {
    const connection = createConnection(serverUrl, roomId);
    connection.connect();
    return () => connection.disconnect();
  }, [serverUrl, roomId]); // ✓ both are used, both are listed
}

You don’t choose the dependencies — your code does. If you leave one out, the effect keeps using a stale value. The react-hooks/exhaustive-deps lint rule (in eslint-plugin-react-hooks) checks this for you; treat its warnings as errors.

If you don’t want an effect to re-run for some value, change the code so it doesn’t need that value: move constants outside the component, move functions inside the effect, or use an Effect Event for non-reactive logic (see Effect events).

Objects and functions as dependencies

Objects and functions created during render are new every render, so an effect that depends on them re-runs every time:

JSX
function SearchResults({ query }) {
  const options = { query, limit: 20 };       // new object every render
  useEffect(() => {
    fetchResults(options).then(setResults);
  }, [options]);                              // ✗ re-runs on every render
}

Depend on primitive values instead, and create the object inside the effect:

JSX
useEffect(() => {
  const options = { query, limit: 20 };
  fetchResults(options).then(setResults);
}, [query]);                                  // ✓ re-runs only when query changes

Always clean up

If your effect subscribes, connects, starts a timer or adds a listener, it must undo it in the cleanup. Otherwise you get memory leaks, duplicate listeners and updates to components that no longer exist.

JSX
useEffect(() => {
  const id = setInterval(() => setSeconds((s) => s + 1), 1000);
  return () => clearInterval(id);
}, []);

Some effects don’t need cleanup — setting document.title, for instance, because the next run simply overwrites it.

Why effects run twice in development

With <StrictMode>, React mounts each component, immediately unmounts it, and mounts it again — in development only. You’ll see “connected, disconnected, connected” in the console. This is deliberate: it simulates a user navigating away and back, and immediately reveals effects with missing or broken cleanup. If your app behaves correctly after setup → cleanup → setup, your effect is correct. Don’t try to prevent it with refs; fix the cleanup.

Effects run after paint

useEffect runs after the browser has painted, which is right for almost everything. If you need to measure the DOM and change something before the user sees it (to avoid a visible flicker — e.g. positioning a tooltip), use useLayoutEffect, which runs synchronously after the DOM updates but before paint. It blocks painting, so use it only when you see a flicker with useEffect.

Common effect patterns

JSX
// Sync with localStorage
useEffect(() => {
  localStorage.setItem('theme', theme);
}, [theme]);

// Control a non-React widget
useEffect(() => {
  const map = new MapLibrary(containerRef.current, { zoom });
  return () => map.destroy();
}, []);

useEffect(() => {
  mapRef.current?.setZoom(zoom);
}, [zoom]);

// Keyboard shortcut
useEffect(() => {
  function handleKeyDown(e) {
    if (e.key === '/' && !e.target.matches('input, textarea')) {
      e.preventDefault();
      searchRef.current?.focus();
    }
  }
  document.addEventListener('keydown', handleKeyDown);
  return () => document.removeEventListener('keydown', handleKeyDown);
}, []);

Data fetching is also an effect in principle, but doing it well (avoiding race conditions, caching, deduplication) takes more care — see Fetching data.

Effects are an escape hatch. They’re for stepping outside React. If no external system is involved, you probably don’t need one — and the next lesson shows how to tell.

Exercise

Window size and a document title

Write a WidthBadge component that shows the current window.innerWidth, updating on resize (add the listener in an effect and remove it in cleanup). Then write UnreadTitle({ count }) that sets document.title to “(N) Academy” when count > 0 and “Academy” otherwise, re-running only when count changes.

JavaScript
import { useEffect, useState } from 'react';

export function WidthBadge() {
  // your code here
}

export function UnreadTitle({ count }) {
  // your code here
}

Summary

  • Effects synchronise a component with something outside React: browser APIs, timers, network connections, third-party widgets.
  • useEffect(setup, deps) runs after React commits; the setup may return a cleanup function.
  • The dependency array lists every reactive value the effect uses; React re-runs the effect when one changes.
  • [] means run once after mounting; leaving the array out means run after every render.
  • In development, StrictMode runs setup → cleanup → setup to prove your cleanup works.