Skip to main content
Saved

Pattern Components Beginner

Component Lifecycle

The framework calls your lifecycle hooks when a component mounts, updates, and unmounts, so you can add listeners, subscriptions, and timers and then remove them again, without leaking memory or showing stale data.

Examples
React, Vue, Svelte and native web
Read
5 min

The problem

If you navigate around your application for a while and check memory usage, you’ll often find it still climbing. Usually that’s because components added event listeners and opened subscriptions that they never removed or closed, and often those components don’t even exist anymore.

The pattern

Anything your component sets up, such as event listeners, subscriptions, and timers, should be undone at the right point in its lifecycle, either when the component unmounts or when the props it depends on change.

Problem

I’ve seen applications where navigating 50 pages created 500 event listeners because components kept adding listeners without ever removing them. Click handlers fired three times per click, and memory usage grew until the browser became unusable.

Missing cleanup also causes race conditions. Request A starts, then request B starts for newer data, but A finishes first and overwrites the newer data with stale information. Without lifecycle cleanup, there’s no place in your code where you can abort the stale request before it finishes.

Solution

On mount, a component sets up event listeners, starts subscriptions, fetches initial data, and opens connections such as WebSockets. On unmount, it reverses all of that by removing listeners, canceling subscriptions, clearing timers, and aborting pending requests. If it skips that step, the listeners and subscriptions stay in memory after the component has gone.

Each time props change, the component cleans up resources tied to the old values and sets up new ones. For example, if the user ID changes, it unsubscribes from the old user’s data stream and subscribes to the new one.

Modern frameworks have lifecycle hooks for this, such as React’s useEffect with a cleanup function, Vue’s onMounted and onUnmounted, and Svelte’s $effect with a returned cleanup function. The framework calls these hooks at the right moments, which is easier and less error-prone than tracking the lifecycle manually.

Example

These examples start with an effect that leaks, then show the same subscription with its cleanup in each framework, and go on to aborting stale requests.

Basic Lifecycle with Cleanup

This effect subscribes when the component mounts, and again each time userId changes, but it never unsubscribes. Each old subscription stays open and keeps calling setData, even after the component has gone, and that’s the leak described in the Problem.

useEffect(() => {
  dataSource.subscribe(userId, setData);
  // Nothing is returned, so nothing ever unsubscribes
}, [userId]);

The fix is to undo the setup in a cleanup, which each framework runs for you at the right time.

import { useEffect, useState } from 'react';

function DataSubscriber({ userId }) {
  const [data, setData] = useState(null);

  useEffect(() => {
    const subscription = dataSource.subscribe(userId, setData);

    // Cleanup runs on unmount or before re-running effect
    return () => subscription.unsubscribe();
  }, [userId]);

  return <div>{data ? data.name : 'Loading...'}</div>;
}

React and Svelte use one effect for all three stages. It runs on mount, it runs again when userId changes, and the function it returns runs before each rerun and on unmount. Vue and custom elements have a separate hook for each stage, which are onMounted, watch, and onUnmounted in Vue, and connectedCallback, attributeChangedCallback, and disconnectedCallback in a custom element.

In React, the array after the effect function is called the dependency array, and it lists the values the effect uses, which is [userId] here. When one of those values changes between renders, React runs the cleanup for the old value and then runs the effect again with the new one. Svelte works out the dependencies from what the effect uses, so it doesn’t need an array.

Preventing Race Conditions with Abort Controllers

This example fixes the race condition described in the Problem, where an older request finishes last and overwrites newer data. When query changes, React runs the cleanup first, and controller.abort() cancels the request for the old query, so only the latest request can call setResults. An aborted fetch rejects with an AbortError, which the catch ignores because the component’s own cleanup caused it.

function SearchResults({ query }) {
  const [results, setResults] = useState([]);

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

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

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

  return <ul>{results.map(r => <li key={r.id}>{r.title}</li>)}</ul>;
}

Handling Multiple Lifecycle Concerns

A component that needs several resources can use one effect for each. Each cleanup is then next to its own setup, and each effect has its own dependencies. Here, a change to userId only replaces the subscription, and the visibility listener stays in place until the component unmounts.

function UserProfile({ userId }) {
  const [user, setUser] = useState(null);
  const [visible, setVisible] = useState(!document.hidden);

  useEffect(() => {
    const subscription = dataSource.subscribe(userId, setUser);
    return () => subscription.unsubscribe();
  }, [userId]);

  // An empty array means set up on mount and clean up on unmount
  useEffect(() => {
    const handleVisibilityChange = () => setVisible(!document.hidden);
    document.addEventListener('visibilitychange', handleVisibilityChange);
    return () => document.removeEventListener('visibilitychange', handleVisibilityChange);
  }, []);

  return <div className={visible ? '' : 'paused'}>{user?.name}</div>;
}

Conditional Effects

Some setup should only happen while a condition is true, such as a price feed that only updates while the user has live updates enabled. Because live is in the dependency array, React runs the cleanup when the user disables live updates, which closes the subscription, and the effect then returns early without opening a new one.

function StockPrice({ symbol, live }) {
  const [price, setPrice] = useState(null);

  useEffect(() => {
    if (!live) return;

    const subscription = priceFeed.subscribe(symbol, setPrice);
    return () => subscription.unsubscribe();
  }, [live, symbol]);

  return <div>{price ?? 'No price yet'}</div>;
}

Benefits

  • Cleaning up properly stops memory leaks, so memory usage doesn’t keep climbing the longer someone has the app open.
  • Aborting stale requests when dependencies change stops old data from overwriting newer data.
  • Effects run at known points, after the component mounts and before it updates or unmounts, so you can tell when each piece of setup and cleanup happens.
  • WebSocket connections are closed and event listeners are removed when the component goes away, instead of staying open in the background.
  • Components respond correctly to prop changes, such as unsubscribing from the old user’s data and subscribing to the new user’s data when the user ID changes.
  • Debugging is easier when side effects are kept together in lifecycle hooks instead of spread across the component.

Tradeoffs

  • You can easily forget a cleanup function, and the resulting memory leaks are hard to diagnose because they don’t cause immediate errors.
  • React’s dependency arrays are easy to get wrong. If you leave out a value, the effect keeps using the value it had when the effect last ran, which is called a stale closure, and if you list a value that the effect itself changes, you can get an infinite loop that crashes the app.
  • A component with five or more effects gets hard to follow and hard to change.
  • React’s useLayoutEffect runs before the browser paints, which avoids a flicker when you need to measure the DOM, but the browser can’t paint until it finishes, so it should only be used where you really need it.
  • Cleanup functions have to be synchronous, so you can’t return a promise. If cleanup involves async work, such as closing a connection, the cleanup function can only start that work, and it returns before the work has finished.
  • Each framework runs its hooks at different times. React’s useEffect usually runs after the browser paints, Vue’s onMounted runs as soon as the component’s DOM has been inserted, before paint, and a custom element’s callbacks run as soon as it’s added to or removed from the document.
  • Testing lifecycle behavior needs careful setup and teardown, because effects from one test can leak into another.

Summary

Every component goes through the same stages, which are mounting, updating, and unmounting. Once you know when each stage happens, you can pair each resource’s setup with a matching cleanup, whether the component is going away or its props have changed. That way memory usage stays steady, and old requests can’t overwrite newer data as users move around your application.

See also

Next in Components Message Thread Storing a conversation as an ordered list of messages, each with a role and its own status, so streaming and errors only affect one turn.

A monthly email
from Den Odell.

What I'm thinking about frontend patterns, plus news when the site changes.

No spam. Unsubscribe anytime.