Skip to main content

useEffect and synchronizing with external systems

useEffect is one of the most misunderstood React Hooks.

The most important mental model is:

What an Effect actually representsEffects are synchronization boundaries, not a generic place for code that happens after rendering.
NOT THISAfter-render bucket

An Effect is not β€œrun arbitrary code after render”.

NOT THIScomponentDidMount replacement

Hook code should not be designed by mechanically translating class lifecycle methods.

MENTAL MODELExternal synchronization

Keep something outside React synchronized with the rendered component's current configuration.

Examples of external systems include:

  • browser APIs;
  • network connections;
  • third-party widgets;
  • subscriptions;
  • timers;
  • analytics systems;
  • media APIs;
  • non-React DOM libraries.
import {useEffect} from 'react';

function ChatRoom({roomId}) {
useEffect(() => {
const connection = createConnection(roomId);
connection.connect();

return () => {
connection.disconnect();
};
}, [roomId]);

return <h1>Room: {roomId}</h1>;
}

The component describes UI. The Effect keeps an external connection synchronized with roomId.

Rendering, events, and Effects are different​

A React component contains three different kinds of logic.

Three kinds of component logicClassify the cause of the work before choosing where it belongs.
RENDERCalculate UI

Pure calculations from the current props, state, and Context.

EVENTRespond to an interaction

Runs because a specific user action such as click, submit, or input happened.

EFFECTSynchronize externally

Runs because the rendered component must keep an external system aligned with its current configuration.

Render logic​

const total = items.reduce((sum, item) => sum + item.price, 0);

This is a calculation. It belongs in render.

Event logic​

function handlePurchase() {
submitOrder(cart);
}

The POST happens because the user clicked Buy. That belongs in the event handler.

Effect logic​

useEffect(() => {
const connection = connectToRoom(roomId);
return () => connection.disconnect();
}, [roomId]);

The connection should exist whenever this rendered room exists. That is synchronization.

Basic syntax​

useEffect(() => {
// start synchronization

return () => {
// stop synchronization
};
}, [dependencies]);

The dependency list is not a scheduling wish list. It describes the reactive values your synchronization process uses.

Effect lifecycle​

Think in terms of start and stop, not mount/update/unmount.

Effect lifecycle as a synchronization processWhen reactive configuration changes, React stops the old process before starting the new one.
1roomId = general
2start general
3roomId β†’ travel
4stop general
5start travel
6component disappears
7stop travel

This model scales better than trying to translate class lifecycle methods into Hook code.

Cleanup​

Cleanup should undo whatever the Effect set up.

Subscription:

useEffect(() => {
function handleOnline() {
setOnline(true);
}

window.addEventListener('online', handleOnline);

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

Timer:

useEffect(() => {
const id = setInterval(refresh, 30_000);

return () => {
clearInterval(id);
};
}, [refresh]);

Connection:

useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();

return () => connection.disconnect();
}, [serverUrl, roomId]);

A good question is:

If this Effect ran, what must happen before it runs again or disappears?

Dependency arrays​

No dependency array​

useEffect(() => {
synchronize();
});

React considers re-synchronization after every commit.

Empty dependency array​

useEffect(() => {
connectOnceForThisMountedInstance();
return disconnect;
}, []);

This says the Effect does not read changing reactive values from the component.

It should not be used to imitate a class lifecycle method by habit.

Reactive dependencies​

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

When roomId changes according to Object.is, React re-synchronizes.

You do not choose dependencies independently from the code​

Bad reasoning:

useEffect(() => {
connect(roomId);
}, []); // ❌ "I only want it once"

The Effect reads roomId. If the component can render with different rooms, the synchronization must follow the current room.

Better:

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

If you disagree with the linter, first ask whether the Effect is designed correctly.

Strict Mode and duplicate setup in development​

In development Strict Mode, React deliberately performs an extra setup β†’ cleanup β†’ setup cycle to expose Effects that are missing cleanup.

Strict Mode stress-tests Effect symmetry
1setup
2cleanup
3setup again

The goal is not to make an Effect "run once despite Strict Mode".

The goal is to make this sequence safe.

Bad workaround:

const didRun = useRef(false);

useEffect(() => {
if (didRun.current) return;
didRun.current = true;

connection.connect();
}, []);

This may hide the development signal while still failing to disconnect when the component actually leaves the screen.

Correct approach:

useEffect(() => {
const connection = createConnection();
connection.connect();

return () => connection.disconnect();
}, []);

Fetching in an Effect​

A client-only app may sometimes fetch inside an Effect:

useEffect(() => {
const controller = new AbortController();

async function load() {
const response = await fetch(`/api/products?q=${query}`, {
signal: controller.signal,
});

const data = await response.json();
setProducts(data);
}

load().catch(error => {
if (error.name !== 'AbortError') {
setError(error);
}
});

return () => controller.abort();
}, [query]);

But raw Effect-based data fetching creates architectural concerns:

  • caching;
  • deduplication;
  • waterfalls;
  • race conditions;
  • loading/error coordination;
  • preloading;
  • server rendering.

Later chapters will compare raw Effects with framework data APIs and server-state libraries.

Race conditions​

Consider two requests:

How an async race can produce stale UICompletion order does not have to match start order.
REQUEST Areact starts first

Starts earlier, but the network response is slower.

REQUEST Bredux starts second

Starts later and finishes first, so its result is the newer intended UI.

A finishes after B

Without cancellation or stale-result protection, the older React request can overwrite the newer Redux result.

Without protection, stale request A might overwrite the newer Redux result.

Cancellation with AbortController, framework loaders, or a data library can prevent this class of bug.

Common infinite loop​

useEffect(() => {
setFiltered(products.filter(matchesQuery));
}, [products, filtered]); // ❌

The Effect updates filtered, which is also a dependency, creating another synchronization cycle.

More importantly, filtered is derived data and likely does not need an Effect at all:

const filtered = products.filter(matchesQuery);

Object and function dependencies​

This creates a new object every render:

const options = {roomId, serverUrl};

useEffect(() => {
connect(options);
}, [options]);

Because the object identity changes, the Effect may reconnect unnecessarily.

Often the cleanest solution is to construct the object inside the Effect:

useEffect(() => {
const options = {roomId, serverUrl};
const connection = connect(options);

return () => connection.disconnect();
}, [roomId, serverUrl]);

Do not add useMemo automatically. First simplify the synchronization boundary.

Effects should represent separate synchronization processes​

Bad:

useEffect(() => {
connectToRoom(roomId);
logVisit(userId);
subscribeToNotifications();
}, [roomId, userId]);

These processes have different reasons to re-synchronize.

Prefer separate Effects when they synchronize independent systems:

useEffect(() => {
const connection = connectToRoom(roomId);
return () => connection.disconnect();
}, [roomId]);

useEffect(() => {
logVisit(userId);
}, [userId]);

Debugging an Effect​

Use this sequence:

Effect debugging flowIf you cannot name the external system, question whether an Effect is needed at all.
1Name the external system
2Identify setup
3Identify cleanup
4List reactive configuration
5Check setup/cleanup symmetry
6Could this be render or event logic?

If you cannot name the external system, the Effect deserves extra scrutiny.

When should I use an Effect?​

Use one when rendering the component requires synchronization with something React does not control.

Examples:

  • WebSocket connection;
  • browser event listener;
  • media playback API;
  • map/chart widget;
  • timer;
  • third-party DOM library;
  • certain client-side network synchronization cases.

When should I NOT use an Effect?​

Usually not for:

  • deriving values from props/state;
  • sorting/filtering for render;
  • responding to a click;
  • resetting one state variable because another changed;
  • notifying a parent about state that the parent could own directly;
  • chaining internal state transitions.

Those cases are covered in You Might Not Need an Effect.

Does this logic belong in an Effect?
Purely calculates UI from current React dataKeep it in render.
Runs because a specific user interaction happenedUse the event handler.
Keeps a browser API, subscription, connection, timer, or third-party system synchronizedAn Effect is appropriate.

Exercise​

Create a ChatRoom component with:

  • roomId prop;
  • simulated connect() and disconnect() methods;
  • correct cleanup;
  • a room selector in the parent.

Log every connect/disconnect and explain why switching rooms produces:

Switching rooms restarts the synchronization
1disconnect old room
2connect new room

Then test under Strict Mode.

Interview questions​

Junior: What problem does useEffect solve?

Mid-level: Why are Effect dependencies determined by reactive values rather than by how often you want the Effect to run?

Senior: How would you decide whether a data-fetching Effect should remain local code or move to framework/server-state infrastructure?

Summary​

Remember:

Effect mental model summary
Render
Calculates UI from current React inputs.
Events
Respond to specific interactions.
Effects
Synchronize with external systems.
Cleanup
Stops or reverses the previous synchronization.
Dependencies
Describe the reactive configuration the process reads.
Design test
If there is no external system, reconsider the Effect.

References​

Next​

Continue with You Might Not Need an Effect.