Blog>
Snippets

Automatic Garbage Collection with Suspense

Explain how Suspense in React 18 can automatically handle the unmounting of asynchronous components and the associated garbage collection.
import { useState, useEffect, Suspense } from 'react';

// Simulate fetching data asynchronously
function fetchData() {
  return new Promise(resolve => {
    setTimeout(() => resolve('Data loaded'), 3000);
  });
}

// A component that fetches data and displays it
function AsyncComponent() {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetchData().then(setData);
  }, []);

  if (!data) return <div>Loading...</div>;

  return <div>{data}</div>;
}

// Usage of Suspense to wrap AsyncComponent
function App() {
  return (
    <Suspense fallback={<div>Waiting for data...</div>}>
      <AsyncComponent />
    </Suspense>
  );
}
In this example, `AsyncComponent` simulates fetching data asynchronously using `fetchData` function which resolves after 3 seconds. It uses React's `useState` and `useEffect` to manage the state of the data. If the data is not yet loaded, it returns a loading message. The `App` component wraps `AsyncComponent` with `Suspense`, providing a fallback UI to be displayed while waiting for the data to load. In React 18, if `App` or `AsyncComponent` unmounts before the data finishes loading, React automatically cleans up and cancels any inflight data fetches, preventing memory leaks.