Skip to content
LATEST

🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.

Upgradix
Upgradix Code. Learn. Ship.
Updated Nov 25, 2026

Side Effects & Lifecycle Sync with useEffect

useEffect lets a React component sync with outside systems like APIs, timers, and browser events after the screen paints. Always return a cleanup function to stop old timers or listeners, and keep your dependency array honest to avoid infinite loops and stale data.

Side Effects & Lifecycle Sync with useEffect

Quick Answer: useEffect lets a React component sync with outside systems like APIs, timers, and browser events after the screen paints. Always return a cleanup function to stop old timers or listeners, and keep your dependency array honest to avoid infinite loops and stale data.

Imagine Arjun opens a live cricket score app on his phone during an India vs. Australia match. He switches between Match 1 and Match 2 every few seconds.

Behind the scenes, the app must fetch live scores, run a 5-second refresh timer, and listen for network drops. If the app forgets to stop old timers when Arjun switches matches, ten timers run at once and drain his battery.

How do we keep React components cleanly synced with APIs, timers, and browser events without leaks or bugs?

1. Why Do We Need useEffect?

The problem without useEffect

Side Effect = any work that reaches outside React, like calling an API, starting a timer, or reading window events.

React components should only calculate UI during render. If you call fetch() or setInterval() directly inside the component body, it runs on every single render.

Example 1: Calling fetch() directly during render (Broken)

This triggers an infinite loop because fetching updates state, which renders again.

function MatchScore({ matchId }) {
  const [score, setScore] = useState("");

  // BAD: Runs on every render -> sets state -> renders again forever!
  fetch(`/api/matches/${matchId}`)
    .then(res => res.json())
    .then(data => setScore(data.score));

  return <h2>{score}</h2>;
}

What happens in the browser

GET /api/matches/IND-AUS (200 OK)
GET /api/matches/IND-AUS (200 OK)
GET /api/matches/IND-AUS (200 OK) ... 500+ requests per minute!
  1. Every state update re-runs the component and fires a brand-new network call.
  2. Old timers and event listeners pile up in memory and never stop.
  3. The browser tab freezes and the backend API gets flooded.

The solution: Lifecycle Sync with useEffect

Dependency Array = the second argument to useEffect that tells React which values should trigger a re-run.

Cleanup Function = the function you return from useEffect so React can cancel old timers, requests, or listeners before running the next effect.

Live Flow: useEffect Lifecycle Sync in Arjun's Cricket App

Watch how React cleans up Match 1 before starting Match 2, keeping active timers safely at 1.

Arjun views: IND vs AUS
Active Timers: 1 Listeners: 1
 
1. Render UI
Arjun picks Match 2. React paints screen first.
2. Cleanup Old
Stops Match 1 timer & aborts old fetch.
3. Run Effect
Fetches Match 2 & starts 1 fresh timer.
4. Unmount
Arjun closes page. All timers & events cleared.
> [Render] Arjun tapped Match 2 (MI vs CSK). UI updated.
UI Render Cleanup Phase Effect Sync Safe Unmount Active Step

React always runs the previous effect's cleanup BEFORE running the new effect. That guarantees zero leaked timers.

2. Fetching Data Safely with AbortController

When Arjun taps Match 1 and quickly taps Match 2, Match 1's slow network response might arrive last and overwrite Match 2's score. This is called a race condition.

Use AbortController inside your cleanup function to cancel stale requests.

Example 2: Fetching live cricket scores with cleanup

Re-runs only when matchId changes and cancels any unfinished request.

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

  async function loadScore() {
    try {
      const res = await fetch(`/api/matches/${matchId}`, {
        signal: controller.signal
      });
      const data = await res.json();
      setScore(data.score);
    } catch (err) {
      if (err.name !== "AbortError") console.error(err);
    }
  }

  loadScore();

  // Cleanup: cancel old request if matchId changes or component unmounts
  return () => controller.abort();
}, [matchId]);

Notice we define async function loadScore() inside the effect. Never make the useEffect callback itself async, because an async function returns a Promise instead of a cleanup function.

3. Subscribing to Browser Events & Cleaning Up Timers

Arjun's app needs two background tasks: checking if his phone goes offline, and polling the score every 5 seconds.

Example 3: Browser event listener + interval timer with cleanup

Always pair addEventListener with removeEventListener and setInterval with clearInterval.

// 1. Subscribe to browser online/offline events once on mount ([])
useEffect(() => {
  const handleOnline = () => setIsOnline(true);
  const handleOffline = () => setIsOnline(false);

  window.addEventListener("online", handleOnline);
  window.addEventListener("offline", handleOffline);

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

// 2. Auto-refresh timer that restarts cleanly when matchId changes
useEffect(() => {
  const timerId = setInterval(() => {
    refreshScore(matchId);
  }, 5000);

  return () => clearInterval(timerId);
}, [matchId]);

When Arjun closes the match screen, React runs both cleanup functions. Zero ghost listeners and zero background timers remain.

4. Dependency Array Rules at a Glance

How the dependency array controls when useEffect runs
Dependency Array When Effect Runs Best Use Case
useEffect(fn) (omitted) After every single render. Rarely needed; usually a bug.
useEffect(fn, []) Once after initial mount only. Global browser listeners like online or resize.
useEffect(fn, [matchId]) On mount, and whenever matchId changes. Fetching data or timers tied to a prop or state.

5. Avoiding Infinite Loops & Stale Closures

1. Infinite loops from updating a dependency

If your effect updates score and also lists score in the dependency array without a guard, it loops forever. Creating a new object or function inside the component body and putting it in the dependency array also causes an infinite loop, because JavaScript treats a new object as changed on every render.

Better approach: Only list primitive values you actually need, or memoize objects/functions with useMemo and useCallback.

2. Stale closures inside timers

Stale Closure = when a timer or listener remembers an old state value from the render when it was created.

Example 4: Fixing a stale closure in a live ball counter

Using prev => prev + 1 always reads the latest state without restarting the timer.

// BAD: "seconds" stays stuck at 0 inside the closure forever
useEffect(() => {
  const id = setInterval(() => setSeconds(seconds + 1), 1000);
  return () => clearInterval(id);
}, []);

// GOOD: Functional update always gets the freshest value
useEffect(() => {
  const id = setInterval(() => setSeconds(prev => prev + 1), 1000);
  return () => clearInterval(id);
}, []);

Design tip: In React Strict Mode during development, React intentionally mounts, cleans up, and mounts your component a second time. If your app breaks or duplicates requests in Strict Mode, your cleanup function is missing or incomplete.

6. Interview Questions & Practice

Question 1: Why does React run my useEffect twice in development?

What the interviewer expects: Understanding of React Strict Mode and why cleanup functions matter.

Strong answer: "In development, React Strict Mode intentionally mounts, runs cleanup, and re-mounts components to stress-test side effects. In Arjun's cricket app, if my 5-second score timer is missing clearInterval, Strict Mode immediately exposes the bug by showing two timers running at once."

Question 2: How do you prevent race conditions when fetching data in useEffect?

What the interviewer expects: Knowledge of AbortController or an ignore boolean flag in the cleanup function.

Strong answer: "When Arjun switches quickly from Match 1 to Match 2, Match 1's slower response could arrive last and overwrite the screen. I pass an AbortController signal to fetch and call controller.abort() in the cleanup function so stale requests are cancelled."

Question 3: What causes a stale closure in useEffect and how do you fix it?

What the interviewer expects: Clear explanation of JavaScript closures + dependency array or functional state updates.

Strong answer: "A stale closure happens when an effect with an empty [] dependency array reads a state variable like seconds. Because the effect never re-runs, it stays locked to the initial value of 0. I fix it either by adding seconds to the dependency array or by using a functional update like setSeconds(prev => prev + 1)."

What interviewers expect at different levels

  • Junior developer: Knows the three dependency array forms and remembers to clear timers and listeners.
  • Senior developer: Handles race conditions with AbortController, avoids stale closures, and knows when NOT to use useEffect (like derived state).
  • Technical architect: Extracts reusable sync logic into custom hooks or data-fetching libraries like TanStack Query to eliminate manual effect boilerplate.

Beginner: Hospital waiting room clock

Create a component that updates the current time every second using setInterval inside useEffect, and stops the timer when the user leaves the screen.

Expected result: The clock ticks every second and logs Timer cleared on unmount.

Intermediate: UPI payment window resize tracker

Subscribe to window.addEventListener("resize", ...) to switch between mobile and desktop QR code layouts, and remove the listener on cleanup.

Hint: Keep the handler function reference in a variable so removeEventListener receives the exact same function.

Advanced: Railway PNR live search with debounce

  • Wait 400 ms after Ravi stops typing his PNR number before calling the API.
  • Cancel the timeout in cleanup if Ravi types another digit before 400 ms.
  • Use AbortController to cancel any in-flight request if a new search starts.

Challenge: Verify in the browser Network tab that typing a 10-digit PNR fires only ONE API call.

7. Next Steps

  • Refactor your data-fetching useEffect into a reusable custom hook like useMatchScore(matchId).
  • Inspect your existing components and remove any useEffect that only computes derived state from props.

Discussion & Comments

0
Guest mode · Login / Register
Post directly as a guest or log in first.

No comments yet

Start the discussion above — ask a question, share a tip, or reply to a comment.

This article is protected. Printing and saving as PDF are disabled.