When does useEffect run?
import { useEffect } from "react";
export function DocumentTitle({ title }) {
useEffect(() => {
document.title = title;
}, [title]);
return null;
}
The first setup follows a committed render. When a dependency changes, React runs the previous cleanup, then the new setup; unmount runs the final cleanup. With no dependency array, setup runs after each commit of the component; with an empty array it has no reactive dependencies, not a global once-only guarantee. With [title], the example synchronizes the browser title on a change. It assumes a single owner of the title; route metadata is preferable when a framework manages it. Effects run only on the client. React may let the browser paint before an effect; do not assume exact paint timing. [1][2]
Dependencies, object identity and infinite loops
import { useEffect } from "react";
export function RoomSubscription({ roomId, subscribe }) {
useEffect(() => {
const unsubscribe = subscribe({ roomId });
return () => {
unsubscribe();
};
}, [roomId, subscribe]);
return null;
}
React compares dependencies with Object.is, not deep equality. An object built during rendering is usually a new reference even when its fields match. Construct request or subscription options inside setup and declare their reactive inputs. Here subscribe is a prop and must be included; if its identity changes unnecessarily, fix the caller rather than omit it. A loop needs a state update plus a resulting dependency change. Inspect both and keep the exhaustive-deps rule enabled. [3][11]
Cleanup, timers and Strict Mode
import { useEffect, useState } from "react";
export function Timer({ intervalMs = 1000 }) {
const [ticks, setTicks] = useState(0);
useEffect(() => {
const timerId = window.setInterval(() => {
setTicks((previous) => previous + 1);
}, intervalMs);
return () => {
window.clearInterval(timerId);
};
}, [intervalMs]);
return <output>{ticks}</output>;
}
A resource belongs to the setup that created it. Clear that exact interval ID, unsubscribe the original listener and disconnect the original connection. A functional state updater reads the previous state without capturing ticks, so a tick does not restart the timer. If intervalMs changes, the previous timer is removed. Root Strict Mode adds a development-only setup/cleanup/setup stress test; suppressing it with a ref can conceal leaks. An empty array is not a license to skip cleanup. [4][6]
Fetching data without race conditions
import { useEffect, useState } from "react";
export function useProduct(productId) {
const [result, setResult] = useState(null);
useEffect(() => {
const controller = new AbortController();
let active = true;
async function loadProduct() {
try {
const response = await fetch(
`/api/products/${encodeURIComponent(productId)}`,
{ signal: controller.signal },
);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const product = await response.json();
if (active) {
setResult({ productId, status: "success", product });
}
} catch (error) {
if (active && !controller.signal.aborted) {
setResult({ productId, status: "error", error });
}
}
}
void loadProduct();
return () => {
active = false;
controller.abort();
};
}, [productId]);
if (result?.productId !== productId) {
return { status: "loading" };
}
return result;
}
A slow response for product A must not overwrite product B. Create a fresh AbortController for each setup, and mark that setup inactive on cleanup. fetch resolves on HTTP 404, so check response.ok before parsing. The hook returns loading for a different ID and ignores results after cleanup. This is a single-result example, not a cache or a runtime schema validator: validate JSON in production, define revalidation for repeated IDs, and prefer framework loaders or a query library when caching, SSR and request deduplication matter. Cancellation does not undo a server-side write. [6][7]
Derived values and user actions do not need effects
export function ProductSummary({ products, onCheckout }) {
const total = products.reduce(
(sum, product) => sum + product.priceInCents,
0,
);
function handleCheckout() {
onCheckout(products);
}
return (
<button type="button" onClick={handleCheckout}>
Checkout ({total} cents)
</button>
);
}
The total is determined by current props, so calculate it during rendering rather than storing a second value in state and synchronizing it later. Integer cents avoid ordinary decimal addition issues for this example; real payment totals belong on the server. Checkout is caused by a button press, so call it in the event handler. Moving it into an effect risks repeated submissions on remount. Use memoization for measured expensive calculations, not as a replacement for correct data ownership. [5]
Reading current values with useEffectEvent
import { useEffect, useEffectEvent } from "react";
export function Heartbeat({ intervalMs, onHeartbeat }) {
const reportHeartbeat = useEffectEvent(() => {
onHeartbeat(Date.now());
});
useEffect(() => {
const timerId = window.setInterval(() => {
reportHeartbeat();
}, intervalMs);
return () => {
window.clearInterval(timerId);
};
}, [intervalMs]);
return null;
}
A heartbeat has two distinct concerns: the interval duration determines when to recreate the timer, while the callback should observe current props. In React 19.2 or later, useEffectEvent separates the second concern. Call it from effect logic, keep it out of dependency arrays and do not use it to hide values that should trigger resynchronization. Older React projects can use a properly declared dependency or restructure their API. [8]
External stores, layout and diagnostics
import { useSyncExternalStore } from "react";
function subscribe(onStoreChange) {
window.addEventListener("online", onStoreChange);
window.addEventListener("offline", onStoreChange);
return () => {
window.removeEventListener("online", onStoreChange);
window.removeEventListener("offline", onStoreChange);
};
}
function getSnapshot() {
return navigator.onLine;
}
function getServerSnapshot() {
return true;
}
export function NetworkIndicator() {
const online = useSyncExternalStore(
subscribe,
getSnapshot,
getServerSnapshot,
);
return <output>{online ? "Online" : "Offline"}</output>;
}
A subscription that drives rendering from an external store is often better expressed using useSyncExternalStore. The example uses an optimistic server snapshot of true, reused during hydration; the actual browser value is read afterward. navigator.onLine is only a connectivity hint, not proof that an API works. Use useLayoutEffect for a necessary pre-paint measurement, not routine networking: it blocks paint. When debugging, trace setup and cleanup for each resource and inspect changes in dependency references rather than adding arbitrary delays. [9][10]
