Skip to main content

Effect lifecycle and dependencies

Effects do not have a component-style lifecycle. An Effect describes a restartable synchronization process.

Effect synchronization lifecycleWhen reactive configuration changes, React stops the old process before starting the new one.
1Start synchronization
2Reactive configuration changes
3Stop old synchronization
4Start new synchronization
5Component disappears
6Stop synchronization

Dependencies exist so React can keep an external process aligned with the current render's configuration.

Reactive values​

Values declared inside a component can differ between renders:

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

roomId, serverUrl, and options are reactive. If an Effect reads a reactive value, that value normally belongs in the dependency list.

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

Dependencies describe synchronization configuration​

Dependencies configure the external process
Effect synchronization
Chat connection
serverUrl
Which server should be used?
roomId
Which room should be joined?

If either value changes, the old connection no longer matches the current React state.

React compares dependencies with Object.is​

Dependency comparison between renders
PREVIOUS RENDERDependencies
https://a.com Β· general
NEXT RENDERDependencies
https://a.com Β· travel
Re-synchronize
Clean up the general-room process, then start the travel-room process.

Objects and functions require extra care because identity can change even when contents appear equivalent.

Stale closures​

function Counter() {
const [count, setCount] = useState(0);

useEffect(() => {
const id = setInterval(() => {
console.log(count);
}, 1000);

return () => clearInterval(id);
}, []); // ❌ count is reactive but omitted
}
Why the interval sees a stale value
1Initial render: count = 0
2Effect creates interval closure
3Empty dependencies keep that process
4Later renders have new count values
5Old interval still sees count = 0

React did not fail to update the closure. The code asked React to keep the synchronization process created by the first render.

Do not suppress the dependency linter casually​

// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(() => {
connection.connect(roomId);
}, []);

Suppressing the rule removes a correctness check.

A dependency feels inconvenient. What should you inspect?
The Effect only derives render dataRemove the Effect and calculate during render
The work is caused by a user actionMove it into the event handler
A value is truly constantMove it outside the component
An object/function only supports the EffectCreate it inside the Effect
Latest data is needed but should not restart synchronizationConsider an Effect Event
The value configures the external processKeep it as a dependency

Move constants outside the component​

const serverUrl = 'https://chat.example.com';

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

Moving a genuinely constant value outside proves it is not reactive.

Create objects inside the Effect​

function ChatRoom({roomId}) {
useEffect(() => {
const options = {
serverUrl: 'https://chat.example.com',
roomId,
};

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

The dependency now expresses the real reactive configuration instead of a newly created object identity.

Functions can cause the same identity problem​

useEffect(() => {
const request = {query, limit: 20};
fetchResults(request);
}, [query]);

Move supporting logic inside the Effect when possible. Simplify before reaching for useCallback.

Separate reactive and non-reactive Effect logic​

Classify values by their role
REACTIVEroomId
Changing it must restart or reconfigure the connection.
LATEST VALUE ONLYtheme
A notification should use the latest theme without reconnecting.

React 19.2's useEffectEvent provides a clearer model for latest-value Effect logic.

Each Effect should model one synchronization process​

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

useEffect(() => {
const subscription = subscribeToPresence(userId);
return () => subscription.unsubscribe();
}, [userId]);
Independent processes deserve independent Effects
Room connection
Starts and stops when roomId changes.
Presence subscription
Starts and stops when userId changes.

Dependency changes and cleanup order​

If roomId changes from general to travel:

Cleanup uses the render that created it
1Render with travel
2Commit travel UI
3Clean up general synchronization
4Start travel synchronization

The cleanup closes over values from the render that created it, so the general cleanup knows which process to stop.

Empty and missing dependency arrays​

An empty array is correct when the Effect reads no reactive component values:

useEffect(() => {
const observer = observeWindowSize();
return () => observer.disconnect();
}, []);

No dependency array means synchronization may run after every render:

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

That is relatively uncommon when an external process has explicit configuration.

State updater functions can remove unnecessary reads​

useEffect(() => {
const id = setInterval(() => {
setCount(current => current + 1);
}, 1000);

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

The updater describes a transition from previous state instead of reading the current render's count.

Debugging dependency loops​

Common Effect loop
1Effect runs
2Effect changes state
3React renders
4Dependency identity changes
5Effect runs again

Ask whether the state update is necessary, whether the value is derived data, whether an object/function is recreated every render, and whether the Effect synchronizes an external system at all.

Production example: subscription architecture​

function StockTicker({symbol}) {
const [price, setPrice] = useState(null);

useEffect(() => {
const subscription = market.subscribe(symbol, nextPrice => {
setPrice(nextPrice);
});

return () => subscription.unsubscribe();
}, [symbol]);

return <output>{price ?? 'Loading…'}</output>;
}
External subscription β†’ React UI
1symbol configures subscription
2Market emits price events
3Subscription updates React state
4React renders current price

Exercise​

Refactor a notification subscription so it reconnects only when userId changes but still uses the latest theme for toasts. Do not disable the linter.

Interview questions​

Junior: What is a reactive value?

Mid-level: Why can object/function dependencies cause repeated Effects?

Senior: How do you distinguish a genuine dependency from non-reactive Effect logic without suppressing exhaustive-deps?

Summary​

Dependency reasoning in one picture
Dependencies
Describe reactive synchronization configuration.
Cleanup
Stops the process created by the previous render.
Restart
Creates a process matching the latest committed configuration.

If a dependency feels wrong, redesign the Effect before overriding the linter.

References​

Next​

Continue with useEffectEvent.