React Effects with useEffect: Synchronizing Systems

Learn when React effects are needed, how dependencies control resynchronization, and how cleanup prevents leaked timers and subscriptions.

published: reading time: 7 min read author: Geek Workbench
Quick Summary

`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

1. When should you use `useEffect`?

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.

2. What belongs in an effect dependency array?

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.

3. Why return a cleanup function?

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.

4. What should happen when an effect dependency changes?

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.
5. Should a click-triggered request start in an effect?

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.
6. Why avoid using an effect to calculate derived state?

A value derived from current props or state can be calculated during render.

  • It avoids an extra render.
  • It avoids keeping two values synchronized.
7. What can happen if a timer has no cleanup?

The timer can keep running after its component disappears.

  • A later mount may add another interval.
  • Return cleanup that clears the timer.
8. Why can a missing dependency leave a stale subscription?

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.
9. Should an effect call setState just to copy a prop?

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.
10. What should an effect do with external data?

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

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.

#react #typescript #state

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.

#react #typescript #accessibility

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.

#react #typescript #state-management