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

Performance Optimization with useEffect

7 min read ยท
In this lesson7

On our cosmic journey through React, performance is critically important - just like managing resources on a spaceship. Suboptimal use of side effects can lead to excessive re-renders, wasted resources, and sluggish application response. In this module, we'll learn how to optimize useEffect to make our applications run smoothly and efficiently.

Performance issues with useEffect

The useEffect hook is a powerful tool, but when used improperly it can cause various problems:

  1. Effects running too frequently - when dependencies change often or are improperly defined
  2. Expensive operations - when performing complex calculations or DOM manipulations inside effects
  3. Cascading updates - when one effect causes state changes that trigger subsequent effects
  4. Unnecessary re-renders - when effects update state even though the data hasn't actually changed

Optimizing the dependency array

The dependency array in useEffect is the key to optimization - it determines when the effect should be re-executed.

Error 1: Too many dependencies

// Problematic code
function AstronautTracker({ team }) {
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const [status, setStatus] = useState('online');

  // This effect will run too frequently
  useEffect(() => {
    console.log(`Tracking astronaut: ${team.leader}`);
    fetchAstronautPosition(team.leader).then(newPosition => {
      setPosition(newPosition);
    });
  }, [team, position, status]); // Unnecessary dependencies: position and status

  return <div>Leader position: {position.x}, {position.y}</div>;
}

Solution: Use only necessary dependencies

// Corrected code
function AstronautTracker({ team }) {
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const [status, setStatus] = useState('online');

  // Effect uses only necessary dependencies
  useEffect(() => {
    console.log(`Tracking astronaut: ${team.leader}`);
    fetchAstronautPosition(team.leader).then(newPosition => {
      setPosition(newPosition);
    });
  }, [team.leader]); // Only necessary dependency

  return <div>Leader position: {position.x}, {position.y}</div>;
}

Technique: Memoizing objects and functions

Objects and functions created during rendering are always "new" from the perspective of dependency comparison. We can optimize this using the useMemo and useCallback hooks:

function SpaceshipDashboard() {
  // Without optimization - config object is recreated on every render
  const config = { speed: 10, fuel: 100 };

  // With optimization - config object is memoized and reused
  const memoizedConfig = useMemo(() => ({ speed: 10, fuel: 100 }), []);

  // Without optimization - handleData function is recreated on every render
  const handleData = (data) => console.log(data);

  // With optimization - handleData function is memoized and reused
  const memoizedHandleData = useCallback((data) => console.log(data), []);

  useEffect(() => {
    // This effect will run only once
    const subscription = spaceApi.subscribe(memoizedConfig, memoizedHandleData);
    return () => subscription.unsubscribe();
  }, [memoizedConfig, memoizedHandleData]); // Dependencies are stable

  return <div>Spaceship</div>;
}

Techniques for optimizing expensive operations

1. Debouncing and throttling

When an effect reacts to rapidly changing values (e.g., user input), it's worth using debouncing or throttling:

function SearchAsteroids({ query }) {
  const [results, setResults] = useState([]);
  const [debouncedQuery, setDebouncedQuery] = useState(query);

  // Debouncing the query - updates no more than every 500ms
  useEffect(() => {
    const timeoutId = setTimeout(() => {
      setDebouncedQuery(query);
    }, 500);

    return () => clearTimeout(timeoutId);
  }, [query]);

  // Search effect runs only when debouncedQuery changes
  useEffect(() => {
    if (debouncedQuery) {
      searchAsteroids(debouncedQuery).then(setResults);
    }
  }, [debouncedQuery]);

  return (
    <div>
      <h2>Search results</h2>
      <ul>
        {results.map(asteroid => (
          <li key={asteroid.id}>{asteroid.name}</li>
        ))}
      </ul>
    </div>
  );
}

2. Avoiding unnecessary state updates

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

  useEffect(() => {
    let isMounted = true;

    fetchStationData(stationId).then(newData => {
      // Update only if the component is still mounted
      if (isMounted) {
        // Update only if data has actually changed
        if (JSON.stringify(data) !== JSON.stringify(newData)) {
          setData(newData);
        }
      }
    });

    return () => {
      isMounted = false;
    };
  }, [stationId]);

  return data ? <StationDisplay data={data} /> : <Loading />;
}

Optimizing effects with asynchronous data

Problem: Race conditions

When an effect performs asynchronous operations, "race conditions" can occur - situations where a newer request finishes before an older one:

// Problematic code - susceptible to race conditions
function AsteroidDetails({ asteroidId }) {
  const [details, setDetails] = useState(null);

  useEffect(() => {
    fetchAsteroidDetails(asteroidId).then(response => {
      setDetails(response); // Possible race condition if asteroidId changes quickly
    });
  }, [asteroidId]);

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

Solution: Canceling stale requests

// Fixed code - protected against race conditions
function AsteroidDetails({ asteroidId }) {
  const [details, setDetails] = useState(null);

  useEffect(() => {
    let isCurrent = true;

    fetchAsteroidDetails(asteroidId).then(response => {
      // Update state only if this is still the current request
      if (isCurrent) {
        setDetails(response);
      }
    });

    return () => {
      isCurrent = false; // Mark that this effect is no longer current
    };
  }, [asteroidId]);

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

Advanced technique: AbortController

For APIs that support AbortController (e.g., fetch), we can actually cancel ongoing requests:

function PlanetScanner({ sector }) {
  const [planets, setPlanets] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true);

    // Creating abort controller
    const controller = new AbortController();
    const signal = controller.signal;

    fetch(`https://api.space/planets?sector=${sector}`, { signal })
      .then(response => response.json())
      .then(data => {
        setPlanets(data);
        setLoading(false);
      })
      .catch(error => {
        if (error.name !== 'AbortError') {
          console.error('Error:', error);
          setLoading(false);
        }
      });

    // Cleanup function cancels the request if the effect is interrupted
    return () => {
      controller.abort();
    };
  }, [sector]);

  return (
    <div>
      {loading ? <Loading /> : (
        <PlanetsList planets={planets} />
      )}
    </div>
  );
}

Separating logic into custom hooks

One of the best ways to optimize is creating custom hooks that encapsulate complex logic and can be reused across components:

// Custom hook for fetching and managing data
function usePlanetData(planetId) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    let isMounted = true;
    setLoading(true);

    fetchPlanetData(planetId)
      .then(result => {
        if (isMounted) {
          setData(result);
          setLoading(false);
        }
      })
      .catch(err => {
        if (isMounted) {
          setError(err);
          setLoading(false);
        }
      });

    return () => {
      isMounted = false;
    };
  }, [planetId]);

  return { data, loading, error };
}

// Using the custom hook
function PlanetProfile({ planetId }) {
  const { data, loading, error } = usePlanetData(planetId);

  if (loading) return <LoadingIndicator />;
  if (error) return <ErrorMessage error={error} />;

  return (
    <div>
      <h1>{data.name}</h1>
      <p>Diameter: {data.diameter} km</p>
      <p>Climate: {data.climate}</p>
    </div>
  );
}

Using the layoutEffect mechanism

In rare cases when you need to perform DOM measurements or synchronize with page layout before rendering, you can use useLayoutEffect instead of useEffect:

function CockpitInterface() {
  const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
  const cockpitRef = useRef(null);

  // useLayoutEffect runs synchronously after all DOM mutations,
  // but before rendering on screen
  useLayoutEffect(() => {
    if (cockpitRef.current) {
      const { width, height } = cockpitRef.current.getBoundingClientRect();
      setDimensions({ width, height });
    }
  }, []);

  return (
    <div ref={cockpitRef} className="cockpit">
      <ControlPanel width={dimensions.width} height={dimensions.height} />
    </div>
  );
}

Note: useLayoutEffect blocks visual rendering, so it should be used sparingly and only when absolutely necessary.

Summary: Best Practices for Optimizing useEffect

  1. Minimize dependencies - use only necessary values in the dependency array
  2. Separate effects - instead of one complex effect, use several simpler ones
  3. Memoize dependencies - use useMemo and useCallback for objects and functions
  4. Use debouncing/throttling - for rapidly changing values
  5. Cancel outdated async operations - avoid race conditions and memory leaks
  6. Create custom hooks - encapsulate complex logic in reusable hooks
  7. Analyze rendering patterns - use React DevTools to detect excessive renders
  8. Avoid infinite loops - always make sure effects don't cause infinite update cycles

By applying these optimization techniques, your React application will run efficiently even with complex operations and large datasets - just as a well-optimized spaceship can cover vast distances with minimal resource consumption.

Code for this lesson: App.jsx
import React, { useState, useEffect, useRef, useCallback } from 'react';

// Demonstrating the dependency array
function DependencyArrayDemo() {
  const [count, setCount] = useState(0);
  const [name, setName] = useState('');
  const [logs, setLogs] = useState([]);

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

  // Effect without dependencies - runs on every render
  const effectRuns = useRef(0);
  useEffect(() => {
    // No setState here: a state change would trigger another render and an infinite loop
    effectRuns.current += 1;
    console.log(`Effect WITHOUT a dependency array (${effectRuns.current})`);
  });

  // Effect with an empty array - only on mount
  useEffect(() => {
    addLog('Effect with [] - only on mount');
  }, []);

  // Effect with a dependency on count
  useEffect(() => {
    addLog(`Effect with [count] - count = ${count}`);
  }, [count]);

  // Effect with a dependency on name
  useEffect(() => {
    if (name) addLog(`Effect with [name] - name = "${name}"`);
  }, [name]);

  return (
    <div className="demo-card">
      <h2>Dependency array</h2>
      <div className="inputs">
        <button onClick={() => setCount(c => c + 1)}>
          Count: {count}
        </button>
        <input
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder="Enter a name..."
        />
      </div>
      <div className="logs">
        {logs.map((log, i) => <div key={i}>{log}</div>)}
      </div>
    </div>
  );
}

// Optimizing fetch requests
function OptimizedFetchDemo() {
  const [searchTerm, setSearchTerm] = useState('');
  const [results, setResults] = useState([]);
  const [loading, setLoading] = useState(false);
  const [fetchCount, setFetchCount] = useState(0);
  const abortControllerRef = useRef(null);

  // Debounced search with cleanup
  useEffect(() => {
    // Cancel the previous request
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
    }

    if (!searchTerm.trim()) {
      setResults([]);
      return;
    }

    // Debounce - wait 500ms before searching
    const timeoutId = setTimeout(() => {
      abortControllerRef.current = new AbortController();

      setLoading(true);
      setFetchCount(c => c + 1);

      // Simulating an API call
      setTimeout(() => {
        const mockResults = [
          `Planet: ${searchTerm}-Prime`,
          `Star: ${searchTerm}-Alpha`,
          `Nebula: ${searchTerm}-Nebula`,
        ];
        setResults(mockResults);
        setLoading(false);
      }, 500);
    }, 500);

    // Cleanup - cancel the timeout and request
    return () => {
      clearTimeout(timeoutId);
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
    };
  }, [searchTerm]);

  return (
    <div className="demo-card">
      <h2>Fetch Optimization</h2>
      <div className="fetch-counter">
        Requests made: <span>{fetchCount}</span>
      </div>
      <input
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
        placeholder="Search for space objects..."
      />
      <div className="results">
        {loading ? (
          <div className="loading">Searching...</div>
        ) : results.length > 0 ? (
          results.map((result, i) => (
            <div key={i} className="result">{result}</div>
          ))
        ) : searchTerm ? (
          <div className="empty">Type to search</div>
        ) : null}
      </div>
      <p className="hint">Debounce 500ms + AbortController</p>
    </div>
  );
}

// Avoiding infinite loops
function InfiniteLoopPreventionDemo() {
  const [data, setData] = useState({ count: 0 });
  const renderCount = useRef(0);
  const [safeMode, setSafeMode] = useState(true);

  // Counting renders
  renderCount.current += 1;

  // DANGEROUS - would cause an infinite loop
  // useEffect(() => {
  //   setData({ count: data.count }); // New object = new reference = re-render
  // }, [data]);

  // SAFE - we use a callback
  const incrementSafe = useCallback(() => {
    setData(prev => ({ count: prev.count + 1 }));
  }, []);

  return (
    <div className="demo-card">
      <h2>Avoiding loops</h2>
      <div className="stats">
        <div className="stat">
          <span className="label">Count:</span>
          <span className="value">{data.count}</span>
        </div>
        <div className="stat">
          <span className="label">Renders:</span>
          <span className="value">{renderCount.current}</span>
        </div>
      </div>
      <button onClick={incrementSafe}>
        Safe increment (useCallback)
      </button>
      <p className="hint">
        Use an updater function instead of a direct reference
      </p>
    </div>
  );
}

// Optimization with useRef instead of state
function UseRefOptimizationDemo() {
  const [, forceRender] = useState(0);
  const clickCountRef = useRef(0);
  const renderCountRef = useRef(0);

  renderCountRef.current++;

  const handleClick = () => {
    clickCountRef.current++;
    // Doesn't cause a re-render!
  };

  return (
    <div className="demo-card">
      <h2>useRef vs useState</h2>
      <div className="comparison">
        <div className="box">
          <h3>useRef (without re-render)</h3>
          <p>Clicks: {clickCountRef.current}</p>
          <button onClick={handleClick}>Click (useRef)</button>
        </div>
        <div className="box">
          <h3>Component renders</h3>
          <p>Count: {renderCountRef.current}</p>
          <button onClick={() => forceRender(n => n + 1)}>
            Force render
          </button>
        </div>
      </div>
      <p className="hint">
        useRef doesn't cause a re-render when the value changes
      </p>
    </div>
  );
}

function App() {
  return (
    <div className="app">
      <h1>Optimizing useEffect</h1>
      <div className="demos">
        <DependencyArrayDemo />
        <OptimizedFetchDemo />
        <InfiniteLoopPreventionDemo />
        <UseRefOptimizationDemo />
      </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. What should the cleanup function in useEffect return?

  2. 2. Why can placing an object directly in the useEffect dependency array cause an infinite loop?

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

Hands-on tasks in the game

  • Vertical ordering

    Arrange the React rendering steps with useEffect in order:

  • Code editor

    Animation Frame Management Hook

  • Code editor

    Debounced Search Implementation

  • Code editor

    Create a TemperatureMonitor component using useEffect to simulate temperature readings every 2 seconds.

  • Vertical ordering

    Arrange the evolution of event handling optimization:

  • Code editor

    Create a CommunicationChannel component with useEffect that establishes a connection and cleans up on unmount.

  • Click in order

    Arrange the useEffect lifecycle:

  • Code editor

    Create an EarthCommunication component using useEffect to fetch data from an API and handle loading/error states.

  • Vertical ordering

    Arrange the useEffect mastery path:

  • Code editor

    Create ColonySettings with useEffect to sync state with localStorage (theme, language, etc.).

  • Code editor

    Create ShipDashboard with useState for fuel/temperature/engine, useEffect with a 2s interval, and buttons to control the systems

  1. Put in orderWhen useEffect Runs
  2. QuestionReturn Value from Cleanup in useEffect
  3. Coding taskPractice: requestAnimationFrame
  4. QuestionObject in Dependency Array
  5. Coding taskPractice: Debouncing
  6. QuestionCleanup Function in useEffect
  7. Coding taskPractice: Side Effects
  8. Put in orderVertical Sort: Event Handling Optimization
  9. Coding taskPractice: Cleanup in useEffect
  10. Click in orderSort: useEffect Lifecycle
  11. QuestionuseEffect Hook Dependencies
  12. Coding taskPractice: Data Fetching
  13. Put in orderVertical Sort: useEffect Mastery Path
  14. Coding taskPractice: localStorage in React
  15. QuestionTesting State and Events
  16. Coding taskPractice: Ship Dashboard

Useful articles