Skip to article content
FrontendXLesson 05 / 40

Effects, Synchronization and Cleanup

Build, explain and debug React 19 interfaces: components, rendering, state, effects, identity, forms and actions, server components, concurrency, performance and testing, ending with architecture and typing work on real component challenges.

intermediate · about 60 minutes · 4 exercises

  • Predict
  • Explain
  • Implement
  • Debug

What you will be able to do

#
  • Synchronize a component with an external system using useEffect.
  • Reason about dependency arrays and cleanup functions.
  • Recognize when an effect is the wrong tool.

Overview

#

Effects synchronize, they do not react

useEffect runs after commit and lets a component synchronize with something outside React: a subscription, a timer, a network connection, a browser API. It is not a general place to run logic. If a value can be computed during render, compute it there.

snippet.tsx
useEffect(() => {
  const id = setInterval(() => setNow(Date.now()), 1000);
  return () => clearInterval(id);
}, []);

The function returns a cleanup that React runs before the next effect and on unmount. Cleanup prevents leaks such as timers, subscriptions and event listeners.

Dependency array

React compares the dependency array with the previous render using Object.is. If any dependency changed, React runs cleanup then the effect again. An empty array means run once after the first commit (and re-run in development under StrictMode). No array means run after every render, which is rarely what you want.

snippet.tsx
useEffect(() => {
  const controller = new AbortController();
  fetch(`/api/users/${userId}`, { signal: controller.signal })
    .then((r) => r.json())
    .then(setUser)
    .catch((e) => { if (e.name !== "AbortError") throw e; });
  return () => controller.abort();
}, [userId]);

StrictMode double-invocation

In development, React StrictMode mounts, unmounts and remounts components to surface missing cleanup. Effects run twice. This is intentional and does not happen in production. If your effect breaks under double-invocation, the effect is not idempotent or the cleanup is missing.

When not to use an effect

Do not use effects to transform data for rendering: compute during render. Do not use effects to react to a user event: put the logic in the event handler. Do not use effects to reset state when a prop changes: use a key to remount, or adjust state during render with the previous-value pattern. Effects that set state from props or other state often cause an extra render pass and a flash.

snippet.tsx
// Prefer this: compute during render.
const fullName = first + " " + last;

// Over this: an effect that sets derived state.
// useEffect(() => setFullName(first + " " + last), [first, last]);

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    In development with StrictMode, how many times does the interval effect run on mount, and how many intervals are active?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.tsx
    useEffect(() => {
      const id = setInterval(tick, 1000);
      return () => clearInterval(id);
    }, []);
    Choose the best answer
  2. Exercise 2Implement

    Implement a useOnlineStatus hook that subscribes to the browser online and offline events and returns a boolean, with correct cleanup.

    starter.tsx
    export function useOnlineStatus(): boolean {
      return true;
    }

    Reveal the reference answer
    reference.tsx
    import { useEffect, useState } from "react";
    
    export function useOnlineStatus(): boolean {
      const [online, setOnline] = useState(() => navigator.onLine);
      useEffect(() => {
        const on = () => setOnline(true);
        const off = () => setOnline(false);
        window.addEventListener("online", on);
        window.addEventListener("offline", off);
        return () => {
          window.removeEventListener("online", on);
          window.removeEventListener("offline", off);
        };
      }, []);
      return online;
    }

    Authored expected output: Returns true when online and false when offline, and removes both listeners on unmount.

    Initialize from navigator.onLine with a lazy initializer, subscribe in an effect, and remove the exact listener references in cleanup. The empty array is correct because the handlers are stable and defined inside the effect.

  3. Exercise 3Debug

    This effect fetches on every render, causing an infinite loop. Explain and fix.

    starter.tsx
    useEffect(() => {
      fetch(`/api/items?q=${query}`)
        .then((r) => r.json())
        .then((data) => {
          setItems(data);
          setQuery(query.trim());
        });
    });

    Reveal the reference answer
    reference.tsx
    useEffect(() => {
      fetch(`/api/items?q=${query}`)
        .then((r) => r.json())
        .then(setItems);
    }, [query]);

    Authored expected output: The fetch runs only when query changes; no infinite loop.

    The effect has no dependency array, so it runs after every render. It also calls setQuery, which changes state and triggers another render. Adding [query] limits runs to query changes, and removing the setQuery call removes the loop.

  4. Exercise 4Explain

    Explain why computing a derived value during render is preferred over storing it in state via an effect.

    starter.tsx
    // Option A
    const visible = items.filter((i) => i.done);
    // Option B
    const [visible, setVisible] = useState([]);
    useEffect(() => setVisible(items.filter((i) => i.done)), [items]);

    Reveal the reference answer
    reference.tsx
    Option A computes the value from current props and state during render, so it is always consistent and adds no extra render. Option B stores a second copy of derived data, which can drift from the source and forces an extra render pass after items change, producing a brief stale frame.

    Authored expected output: A written explanation of consistency and the extra render pass.

    State that can be derived is duplicated state. Duplicated state can become inconsistent and costs an additional render. Compute it during render unless the computation is genuinely expensive, in which case useMemo.

Common misconceptions

#
  • useEffect is a lifecycle hook with mount and update phases. It synchronizes with external systems after commit.
  • An empty dependency array guarantees one run. In development StrictMode runs it twice to test cleanup.
  • Effects are the right place for derived state. Derived values belong in render; effects add extra renders.
  • Returning a cleanup is optional. Any effect that subscribes or schedules must clean up.

Follow-up practice

#
  • react-data-fetching-and-transitions
  • react-debugging-and-error-handling

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.