JavaScript and React course ยท Module 5: useEffect and Custom Hooks

Advanced Effects - Race Conditions and Debouncing

6 min read ยท
In this lesson6

In the previous module, you learned the basics of useEffect optimization: properly choosing dependencies, using isCurrent flags to prevent race conditions, and simple debouncing. Time for advanced techniques - like a true engineering officer on a spaceship, you must know not only the basic procedures but also emergency protocols for the most complex situations.

AbortController - canceling requests

A simple isCurrent flag has a drawback: the request continues running in the background, consuming network resources. When the user quickly switches between pages, dozens of useless requests may be running in the background. It's like sending radio signals to stations you've already flown away from - you're wasting transmitter power.

AbortController is a built-in browser mechanism that allows you to actually cancel an HTTP request, rather than just ignoring its result.

function PlanetDetails({ planetId }) {
  const [planet, setPlanet] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    // Creating controller to cancel request
    const abortController = new AbortController();

    setLoading(true);
    setError(null);

    fetch(`/api/planets/${planetId}`, {
      signal: abortController.signal  // Passing signal to fetch
    })
      .then(res => res.json())
      .then(data => {
        setPlanet(data);
        setLoading(false);
      })
      .catch(err => {
        // AbortError means the request was intentionally cancelled
        if (err.name !== 'AbortError') {
          setError(err.message);
          setLoading(false);
        }
        // If AbortError - we do nothing because the component no longer exists
      });

    // Cleanup: cancel request when planetId changes or component unmounts
    return () => abortController.abort();
  }, [planetId]);

  if (loading) return <p>Loading planet data...</p>;
  if (error) return <p>Error: {error}</p>;
  return <h2>{planet?.name}</h2>;
}

The key difference: with an isCurrent flag, the request continues in the background and consumes bandwidth. With AbortController, the browser actually interrupts the network connection. For large files or slow connections, this is a huge saving.

Race conditions - deeper analysis

A race condition in the React context is a situation where the result of an asynchronous operation arrives at the component at the wrong moment. Imagine: an astronaut clicks on planet Mars, then quickly on Jupiter. The request for Mars takes 2 seconds, the one for Jupiter 0.5 seconds. Jupiter returns first - we correctly display Jupiter. But after 2 seconds Mars comes back and overwrites Jupiter's data!

// PROBLEM: Race condition without protection
function StarMap({ starId }) {
  const [star, setStar] = useState(null);

  useEffect(() => {
    // Every starId change triggers a new fetch
    // But the previous fetch is still running in the background!
    fetchStarData(starId).then(data => {
      setStar(data); // May overwrite newer data!
    });
  }, [starId]);

  return <div>{star?.name}</div>;
}

// SOLUTION: AbortController eliminates the race condition
function StarMap({ starId }) {
  const [star, setStar] = useState(null);

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

    fetchStarData(starId, { signal: controller.signal })
      .then(data => setStar(data))
      .catch(err => {
        if (err.name !== 'AbortError') console.error(err);
      });

    return () => controller.abort(); // Cancel previous request
  }, [starId]);

  return <div>{star?.name}</div>;
}

Stale closures - the trap of outdated values

A stale closure is a subtle bug that appears when a callback inside useEffect "sees" an old version of a state variable. It's like reading yesterday's sensor report thinking it's current data.

// PROBLEM: Stale closure
function AsteroidCounter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const timer = setInterval(() => {
      // This function "sees" count from when the timer was created = always 0!
      setCount(count + 1); // Always sets to 1 because count = 0
    }, 1000);

    return () => clearInterval(timer);
  }, []); // Empty array = effect runs once, count closed over 0

  return <p>Asteroids: {count}</p>;
}

// SOLUTION 1: Use functional updater
function AsteroidCounter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const timer = setInterval(() => {
      // Functional updater always receives the current value!
      setCount(prevCount => prevCount + 1);
    }, 1000);

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

  return <p>Asteroids: {count}</p>;
}

// SOLUTION 2: Use useRef for values that must be current
function TrajectoryCalculator() {
  const [velocity, setVelocity] = useState(100);
  const velocityRef = useRef(velocity);

  // Synchronize ref with the latest value
  useEffect(() => {
    velocityRef.current = velocity;
  }, [velocity]);

  useEffect(() => {
    const timer = setInterval(() => {
      // ref.current always has the latest value
      console.log('Current velocity:', velocityRef.current);
    }, 1000);

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

  return <input value={velocity} onChange={e => setVelocity(Number(e.target.value))} />;
}

Rule: If a callback in setInterval or setTimeout needs the current state value, use a functional updater (setState(prev => ...)) or useRef.

Advanced cleanup patterns

The cleanup function in useEffect is not just clearInterval. In real applications, you need to clean up many types of resources simultaneously.

function LiveDashboard({ stationId }) {
  const [data, setData] = useState(null);

  useEffect(() => {
    const controller = new AbortController();
    let eventSource = null;
    let reconnectTimer = null;

    // 1. Fetching initial data
    fetch(`/api/station/${stationId}`, { signal: controller.signal })
      .then(res => res.json())
      .then(setData)
      .catch(err => {
        if (err.name !== 'AbortError') console.error(err);
      });

    // 2. Server-Sent Events for live updates
    function connectSSE() {
      eventSource = new EventSource(`/api/station/${stationId}/live`);
      eventSource.onmessage = (event) => {
        setData(JSON.parse(event.data));
      };
      eventSource.onerror = () => {
        eventSource.close();
        // Reconnect after 5 seconds
        reconnectTimer = setTimeout(connectSSE, 5000);
      };
    }
    connectSSE();

    // 3. Cleanup: close ALL resources
    return () => {
      controller.abort();              // Cancel fetch
      if (eventSource) eventSource.close();  // Close SSE
      if (reconnectTimer) clearTimeout(reconnectTimer); // Cancel reconnect
    };
  }, [stationId]);

  return <div>{data?.status}</div>;
}

Debounce with cleanup - the correct pattern

In the previous module you learned simple debouncing. Now let's see a pattern that properly handles cleanup and avoids memory leaks:

function useDebounce(value, delay) {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    // Set timer to update debounced value
    const timer = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    // Cleanup: cancel timer if value changes before delay expires
    return () => clearTimeout(timer);
  }, [value, delay]);

  return debouncedValue;
}

// Usage in a search component
function GalaxySearch() {
  const [query, setQuery] = useState('');
  const debouncedQuery = useDebounce(query, 400);
  const [results, setResults] = useState([]);

  // This effect runs only after 400ms from the last character
  useEffect(() => {
    if (!debouncedQuery) {
      setResults([]);
      return;
    }

    const controller = new AbortController();

    fetch(`/api/search?q=${debouncedQuery}`, { signal: controller.signal })
      .then(res => res.json())
      .then(setResults)
      .catch(err => {
        if (err.name !== 'AbortError') console.error(err);
      });

    return () => controller.abort();
  }, [debouncedQuery]);

  return (
    <div>
      <input value={query} onChange={e => setQuery(e.target.value)} placeholder="Search the galaxy..." />
      <ul>
        {results.map(r => <li key={r.id}>{r.name}</li>)}
      </ul>
    </div>
  );
}

Notice how we combine three patterns: custom hook (useDebounce), AbortController, and cleanup. This is a typical pattern in professional React applications.

Summary

Advanced effect management techniques:

  1. AbortController - cancel requests instead of ignoring responses. Saves bandwidth and resources.
  2. Race conditions - use AbortController or cancel flags to prevent newer data from being overwritten by older data.
  3. Stale closures - use functional updater (setState(prev => ...)) or useRef in timer callbacks.
  4. Complex cleanup - close all resources: fetch, SSE, timers, event listeners.
  5. Debounce + AbortController - combine both patterns for optimal searching.
Code for this lesson: App.jsx
import React, { useState, useEffect, useRef, useCallback } from 'react';

// === Custom Hook: useDebounce ===
function useDebounce(value, delay) {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const timer = setTimeout(() => setDebouncedValue(value), delay);
    return () => clearTimeout(timer);
  }, [value, delay]);

  return debouncedValue;
}

// === Demo 1: AbortController ===
function AbortControllerDemo() {
  const [planetId, setPlanetId] = useState(1);
  const [planet, setPlanet] = useState(null);
  const [loading, setLoading] = useState(false);
  const [log, setLog] = useState([]);

  const addLog = useCallback((msg) => {
    setLog(prev => [...prev.slice(-6), `[${new Date().toLocaleTimeString()}] ${msg}`]);
  }, []);

  useEffect(() => {
    const controller = new AbortController();
    setLoading(true);
    addLog(`Fetch planet #${planetId} - START`);

    // Simulating fetch with AbortController
    const timer = setTimeout(() => {
      if (!controller.signal.aborted) {
        const planets = ['Mercury','Venus','Earth','Mars','Jupiter','Saturn','Uranus','Neptune'];
        setPlanet({ id: planetId, name: planets[(planetId - 1) % planets.length] });
        setLoading(false);
        addLog(`Fetch planet #${planetId} - OK`);
      }
    }, 800 + Math.random() * 1200);

    return () => {
      controller.abort();
      clearTimeout(timer);
      addLog(`Fetch planet #${planetId} - CANCELLED`);
    };
  }, [planetId, addLog]);

  return (
    <div className="demo-card">
      <h2>AbortController</h2>
      <p className="info">Click quickly - see the cancellation!</p>
      <div className="controls-row">
        {[1,2,3,4,5].map(id => (
          <button key={id}
            className={planetId === id ? 'active' : ''}
            onClick={() => setPlanetId(id)}>
            #{id}
          </button>
        ))}
      </div>
      <div className="result">
        {loading ? 'Loading...' : planet ? `Planet: ${planet.name}` : 'Choose a planet'}
      </div>
      <div className="log">
        {log.map((l, i) => (
          <div key={i} className={l.includes('CANCELLED') ? 'log-abort' : l.includes('OK') ? 'log-ok' : 'log-start'}>
            {l}
          </div>
        ))}
      </div>
    </div>
  );
}

// === Demo 2: Stale Closure ===
function StaleClosureDemo() {
  const [count, setCount] = useState(0);
  const [badCount, setBadCount] = useState(0);
  const [running, setRunning] = useState(false);

  // BUG: stale closure - count locked at 0
  useEffect(() => {
    if (!running) return;
    const timer = setInterval(() => {
      setBadCount(badCount + 1); // Always sees badCount=0!
    }, 500);
    return () => clearInterval(timer);
  }, [running]); // badCount not in dependencies = stale closure

  // FIX: functional updater
  useEffect(() => {
    if (!running) return;
    const timer = setInterval(() => {
      setCount(prev => prev + 1); // Always the current value!
    }, 500);
    return () => clearInterval(timer);
  }, [running]);

  const reset = () => {
    setRunning(false);
    setCount(0);
    setBadCount(0);
  };

  return (
    <div className="demo-card">
      <h2>Stale Closure</h2>
      <div className="comparison">
        <div className="bad">
          <h3>BUG: count + 1</h3>
          <div className="big-number">{badCount}</div>
          <p>Frozen at 1!</p>
        </div>
        <div className="good">
          <h3>FIX: prev =&gt; prev + 1</h3>
          <div className="big-number">{count}</div>
          <p>Increases correctly!</p>
        </div>
      </div>
      <div className="controls-row">
        <button onClick={() => setRunning(true)} disabled={running}>Start</button>
        <button onClick={reset}>Reset</button>
      </div>
    </div>
  );
}

// === Demo 3: Debounce + AbortController ===
function DebouncedSearchDemo() {
  const [query, setQuery] = useState('');
  const debouncedQuery = useDebounce(query, 400);
  const [results, setResults] = useState([]);
  const [searchCount, setSearchCount] = useState(0);
  const [keystrokeCount, setKeystrokeCount] = useState(0);

  useEffect(() => {
    if (!debouncedQuery) {
      setResults([]);
      return;
    }

    const controller = new AbortController();
    setSearchCount(c => c + 1);

    // Simulating a search
    const stars = [
      'Sirius', 'Betelgeuse', 'Rigel', 'Vega', 'Altair',
      'Deneb', 'Polaris', 'Antares', 'Aldebaran', 'Spica',
      'Procyon', 'Achernar', 'Capella', 'Arcturus', 'Canopus'
    ];

    const timer = setTimeout(() => {
      if (!controller.signal.aborted) {
        const filtered = stars.filter(s =>
          s.toLowerCase().includes(debouncedQuery.toLowerCase())
        );
        setResults(filtered);
      }
    }, 200);

    return () => {
      controller.abort();
      clearTimeout(timer);
    };
  }, [debouncedQuery]);

  const handleInput = (e) => {
    setQuery(e.target.value);
    setKeystrokeCount(c => c + 1);
  };

  return (
    <div className="demo-card">
      <h2>Debounce + Abort</h2>
      <input
        className="search-input"
        placeholder="Search for a star (e.g. Sir, Bet, Rig)..."
        value={query}
        onChange={handleInput}
      />
      <div className="stats-row">
        <span>Keystrokes: {keystrokeCount}</span>
        <span>Requests: {searchCount}</span>
        <span>Saved: {Math.max(0, keystrokeCount - searchCount)}</span>
      </div>
      {results.length > 0 && (
        <div className="results">
          {results.map(r => <div key={r} className="result-item">{r}</div>)}
        </div>
      )}
      {debouncedQuery && results.length === 0 && (
        <p className="no-results">No results for "{debouncedQuery}"</p>
      )}
    </div>
  );
}

function App() {
  return (
    <div className="app">
      <h1>Advanced Effects</h1>
      <div className="demos">
        <AbortControllerDemo />
        <StaleClosureDemo />
        <DebouncedSearchDemo />
      </div>
    </div>
  );
}

export default App;

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Which of the following resources requires a cleanup function in useEffect?

  2. 2. How do you prevent race conditions when fetching data in useEffect (e.g., quickly switching between pages)?

These are 2 of 7 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Click in order

    Arrange the event listener setup:

  • Vertical ordering

    Arrange the order of hook execution during rendering:

  • Click in order

    Arrange the cleanup function for a timer in useEffect:

  • Vertical ordering

    Order the steps for preventing memory leaks in useEffect - from identification to resolution:

  • Click in order

    Arrange the custom hook:

  • Click in order

    Arrange the async invocation pattern in useEffect:

  • Vertical ordering

    Arrange the steps for handling fetch with AbortController in useEffect:

  • Vertical ordering

    Order the effect lifecycle with cleanup when dependencies change:

  • Horizontal ordering

    Arrange the custom hook declaration elements from left to right:

  • Vertical ordering

    Order the effect lifecycle in useEffect:

  1. Click in orderEvent Listener Setup
  2. Put in orderuseLayoutEffect
  3. QuestionEffect Cleanup Strategies
  4. QuestionRace Conditions in useEffect
  5. Click in orderClearing a Timer in useEffect
  6. QuestionPerformance Optimizations
  7. Put in orderMemory Leaks and useEffect
  8. Click in orderCustom Hook Pattern
  9. Click in orderAsync Functions in useEffect
  10. QuestionuseRef in Library Integration
  11. Put in orderAbortController in useEffect
  12. QuestionTesting Cleanup in useEffect
  13. Put in orderCleanup Function in useEffect
  14. QuestionCreating Custom Hooks
  15. Put in orderCustom Hook Declaration
  16. Put in orderuseEffect Lifecycle
  17. QuestionEffect Composition Patterns

Useful articles