React Effects with useEffect: Synchronizing Systems
Learn when React effects are needed, how dependencies control resynchronization, and how cleanup prevents leaked timers and subscriptions.
`useEffect` keeps browser timers, subscriptions, and other external systems synchronized with a component. This guide contrasts effects with render-time calculations and event handlers, then shows dependencies and cleanup in a typed timer example. Include every reactive value an effect reads, and stop old work during cleanup to avoid leaks and stale subscriptions.
React effects with useEffect: synchronizing external systems
Introduction
An effect connects a component to something React does not manage, such as a timer, browser event, or subscription. It runs after render. Derive values while rendering and handle click work in its event handler; reserve effects for external synchronization.
This article explains dependency-driven resynchronization and cleanup with a browser timer and a subscription-style lifecycle.
Render, event, or effect?
Calculate values from props or state during render. Put work caused by a specific action in its handler. Neither needs an effect:
interface ProfileActionsProps {
firstName: string;
lastName: string;
onSave: (name: string) => void;
}
function ProfileActions({ firstName, lastName, onSave }: ProfileActionsProps) {
const fullName = `${firstName} ${lastName}`;
return (
<button type="button" onClick={() => onSave(fullName)}>
Save {fullName}
</button>
);
}
An effect is different: it synchronizes with something outside React, such as the timer in the next example.
Start and stop a timer
This typed component keeps a clock display in sync with a browser timer. The effect sets up the interval after render and returns cleanup to stop it when the component is removed.
import { useEffect, useState } from "react";
function Clock() {
const [now, setNow] = useState<number>(() => Date.now());
useEffect(() => {
const timerId: number = window.setInterval(() => {
setNow(Date.now());
}, 1000);
return () => window.clearInterval(timerId);
}, []);
return <time>{new Date(now).toLocaleTimeString()}</time>;
}
The empty dependency array means this effect does not depend on changing props or state. If an effect reads a reactive value, list it as a dependency. React runs cleanup for the old values before setting up again with new values, then runs cleanup when the component unmounts.
For example, a useEffect that subscribes to a roomId should include [roomId] and unsubscribe from the old room in its cleanup before joining the new one. A subscription, event listener, or timer should have a matching teardown.
This browser subscription tracks online and offline events. The setup reports the current state, and cleanup removes both listeners:
function useOnlineStatus() {
const [isOnline, setIsOnline] = useState(true);
useEffect(() => {
const updateStatus = () => setIsOnline(navigator.onLine);
window.addEventListener("online", updateStatus);
window.addEventListener("offline", updateStatus);
updateStatus();
return () => {
window.removeEventListener("online", updateStatus);
window.removeEventListener("offline", updateStatus);
};
}, []);
return isOnline;
}
navigator.onLine is a connectivity hint; it does not tell you whether a particular API is reachable.
Lifecycle flow
flowchart TD
A[Render with current values] --> B[Effect setup]
B --> C{Next lifecycle step?}
C -->|Dependencies changed| D[Cleanup old effect]
D --> E[Setup with new values]
C -->|Unmount| F[Cleanup effect]
Trade-off table
| Approach | Use it when | Watch for |
|---|---|---|
| Render-time calculation | A value comes from current props or state | Avoid storing a duplicate |
| Event handler | Work follows a specific user action | Keep action logic in the handler |
| Effect with cleanup | An external system must stay synchronized | Dependencies and teardown must be correct |
Production failure scenarios
If a clock effect starts an interval but forgets clearInterval, navigating away leaves the timer running. Mounting the page again can create a second timer, causing extra updates and battery use. Return cleanup from the effect and test the setup/cleanup path. A missing dependency can also leave a subscription connected to an old room ID; include the changing value so React cleans up and reconnects.
Common pitfalls / anti-patterns
Common problems include missing dependencies, unstable objects that retrigger effects, and using an effect to copy derived data into state. Let the linter identify missing dependencies, then restructure code instead of suppressing the warning.
Security and compliance notes
Effects run in the browser, where API responses and URL values are untrusted. Validate data before using it. Do not put secrets in client code or logs. An effect does not make unsafe data safe.
Observability checklist
- Track failed requests and subscription reconnects.
- Confirm timers and listeners are cleaned up.
- Record safe IDs, not sensitive payload contents.
When to use / when not to use
Use an effect to synchronize with a timer, subscription, or browser API. Keep derived values in render and click-triggered work in the event handler. Do not add an effect just to copy props into state or calculate a value already available during rendering.
Quick recap checklist
- Derive values during rendering when possible.
- Put click-triggered work in its event handler.
- Use effects to synchronize with timers, subscriptions, and browser APIs.
- List reactive dependencies and clean up the old synchronization.
- Validate external data and avoid logging private values.
Interview questions
Use it to synchronize a rendered component with an external system, such as a timer or subscription. Derive values in render and handle click-specific work in the event handler.
Include reactive props, state, and component-scope values the effect reads. When one changes, React cleans up the old effect and sets up the new one.
Cleanup stops or removes external work, such as an interval or event listener. It runs before resynchronizing with changed dependencies and when the component unmounts.
React cleans up the previous synchronization and sets up the effect with the new value.
- Include reactive values read by the effect.
- Clean up subscriptions or timers associated with the previous value.
Usually, put work caused by a specific click in that event handler.
- Effects synchronize with rendered values and external systems.
- Event handlers make the cause of the request clear.
A value derived from current props or state can be calculated during render.
- It avoids an extra render.
- It avoids keeping two values synchronized.
The timer can keep running after its component disappears.
- A later mount may add another interval.
- Return cleanup that clears the timer.
The effect may keep using a value from an earlier render.
- Include the changing subscription key or room ID.
- Unsubscribe from the old value during cleanup.
Usually no. Read the prop directly or calculate a derived value during render.
- Only keep separate state when it represents an independent value.
- Effects are for synchronizing external systems.
Treat responses and URL values as untrusted runtime input.
- Validate the data before using it.
- Keep secrets and private payloads out of client code and logs.
Further reading
- For render snapshots and state setters, read React state with useState.
- See React custom hooks for extracting reusable effect-backed behavior.
- Fetching and typing API data covers request cancellation and validation.
- Compare request presentation in loading and error states.
- Check effect setup and cleanup through component and interaction tests.
- Read React’s useEffect reference and guides to synchronizing with effects and effect lifecycles.
Conclusion
Use effects for synchronization with systems React does not control. Keep derivation and click logic in their natural places, list the values the effect reads, and clean up timers or subscriptions as they change or end.
Category
Related Posts
React State with useState and TypeScript
Learn how useState snapshots work, how TypeScript infers state types, and how to update objects and arrays immutably in React components.
Accessible React UI: Semantics, Labels, and Keyboard Use
Build React interfaces with semantic controls, connected labels, visible keyboard focus, and status announcements through practical TypeScript examples.
Advanced React State: When Local State Stops Fitting
Learn when React state needs a reducer and context, when Redux Toolkit helps, and why server data often belongs in a query cache instead.