Synchronizing with effects
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
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:
- A setup function containing the code to synchronise. It may return a cleanup function that undoes what setup did.
- 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:
function ChatRoom({ roomId }) {
useEffect(() => {
const connection = createConnection(roomId);
connection.connect();
return () => connection.disconnect();
}, [roomId]);
return <h1>Welcome to #{roomId}</h1>;
}- Mount: the component appears → setup runs → connect to
general. - Dependencies change:
roomIdbecomesmusic→ cleanup runs with the old values (disconnectgeneral), then setup runs with the new ones (connectmusic). - Re-render with same dependencies: nothing happens.
- 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.
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:
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:
useEffect(() => {
const options = { query, limit: 20 };
fetchResults(options).then(setResults);
}, [query]); // ✓ re-runs only when query changesAlways 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.
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
// 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.
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.
import { useEffect, useState } from 'react';
export function WidthBadge() {
// your code here
}
export function UnreadTitle({ count }) {
// your code here
}import { useEffect, useState } from 'react';
export function WidthBadge() {
const [width, setWidth] = useState(() => window.innerWidth);
useEffect(() => {
function handleResize() {
setWidth(window.innerWidth);
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return <span className="badge">{width}px</span>;
}
export function UnreadTitle({ count }) {
useEffect(() => {
document.title = count > 0 ? `(${count}) Academy` : 'Academy';
}, [count]);
return null;
}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.