How Suspense Handles Readiness

Suspense gives React components a way to delay rendering until they are "ready." While data fetching is the most discussed application, image preloading is another case where the pattern reduces layout instability — the staggering and jumping known as content reflow that occurs when images download and render after a screen has already appeared.

Suspense relies on two mechanisms. The first is component suspension: when React tries to render a component that is not ready, the component throws a promise. React catches it, renders the nearest fallback in the component tree, and re-attempts rendering once the promise resolves. The second is the transition state update, in which state is set with the instruction that a suspension should not trigger a fallback; the current screen stays visible until the update is ready, and a pending boolean exposes whether the update is still in flight.

Building a Preloading Component

The goal is a <SuspenseImage> component that takes a src attribute, preloads the image, throws while loading, and renders an <img> once ready. Two pieces are required: preloading an image and wiring up the exception.

The first is simple. Beyond the HTML <img src="some-image.png">, JavaScript can create images imperatively with the Image() object, which fires an onload callback once the image has loaded.

const img = new Image();
img.onload = () => {
  // image is loaded
}; 

The naive way to combine preloading with exception throwing fails:

const SuspenseImg = ({ src, ...rest }) => {
  throw new Promise((resolve) => {
    const img = new Image();
    img.onload = () => {
      resolve();
    };
  });
  return <img alt="" src={src} {...rest} />;
}; 

This approach throws on every render attempt, because a new promise is created each time. What is needed is a layer of indirection: an image cache. Reading a src from the cache checks whether the image is loaded; if not, the preload begins and the exception is thrown. If it is loaded, the read returns true and React continues rendering.

export const SuspenseImg = ({ src, ...rest }) => {
  imgCache.read(src);
  return <img src={src} {...rest} />;
};
const imgCache = {
  __cache: {},
  read(src) {
    if (!this.__cache[src]) {
      this.__cache[src] = new Promise((resolve) => {
        const img = new Image();
        img.onload = () => {
          this.__cache[src] = true;
          resolve(this.__cache[src]);
        };
        img.src = src;
      }).then((img) => {
        this.__cache[src] = true;
      });
    }
    if (this.__cache[src] instanceof Promise) {
      throw this.__cache[src];
    }
    return this.__cache[src];
  }
};

Putting It Together

A fallback is defined by placing a Suspense tag in the component tree and passing the fallback through the fallback prop. A suspending component searches upward for the nearest Suspense tag; if none exists, React throws an error. A real application would typically have many Suspense tags for specific modules and fallbacks rendered as an empty shell of the actual component, but the demo needs only a single one wrapping the root app.

function App() {
  return (
    <Suspense fallback={<Loading />}>
      <ShowImages />
    </Suspense>
  );
}

The initial load shows the spinner until the first images are ready, at which point they all appear at once, without staggered reflow.

Transition Updates for Subsequent Batches

Loading a second batch of images should keep the existing ones on screen while the new ones load. The useTransition hook handles this: it returns a startTransition function and an isPending boolean indicating that the state update is in progress, whether it has suspended or is simply slow. Calling useTransition also requires a timeoutMs value, the maximum time isPending may be true before React gives up and renders the fallback. The demo allows 10 seconds — long in real life, but useful when experimenting with throttled networks in DevTools.

const [startTransition, isPending] = useTransition({ timeoutMs: 10000 });

When the button to load more images is clicked, the state update triggers a new query through micro-graphql-react, which is Suspense-compatible and throws a promise while the query is in flight. Once data arrives, the component attempts to render and suspends again while the images preload. Throughout, isPending is true, allowing a loading spinner to display on top of the existing content.

startTransition(() => {
  setPage(p => p + 1);
});

Why There Is No Waterfall

A list of suspending images does not render one suspended image after another. React does not stop when it hits a suspension; it continues rendering all other paths through the component tree, attempts images 1 through N, and only then suspends. Each image in the batch therefore hits the network immediately, and manually preloading the full list beforehand is unnecessary. This is visible in the Network tab of the demo: clicking "Next images" adds the whole bucket at once, resolves them one by one, and displays the results when all are finished. A "Fast 3G" throttle amplifies the effect.

A waterfall can be forced, for demonstration, by reading each image from the cache before React renders the component and walking every path through the tree:

images.forEach((img) => imgCache.read(img));

Suspend Late and Low

The general rule is to suspend as late in rendering and as low in the component tree as possible. Each image in an <ImageList> should suspend in its own component so React can reach each separately without one blocking the others. For data fetching, the equivalent is loading data as late as possible by the components that need it; two queries fetched in a single component would suspend in sequence — query one, then query two — creating a waterfall, unless both are preloaded manually.

Timeouts and Demo Details

// cache read method in the full demo

Waiting indefinitely for one or two slow images is undesirable, so the cache's read method includes a timeout that gives the green light after a set period even if an image is not ready. Users may see an image flicker in, but that is preferable to a frozen interface. Seven seconds is excessive in most contexts, but reasonable for a demo where network throttling is expected. The demo (which must be run with "Disable Cache" unchecked in the DevTools Network tab) subtracts this timeout from the timeoutMs passed to useTransition, getting very close to showing the fallback, while bailing out of the suspend after seven seconds. Unchecking the precache images checkbox swaps the <SuspenseImage> component for a plain <img> tag, allowing a comparison with "normal React" (do not toggle it while results are arriving, or the whole UI may suspend and render the fallback). As with any CodeSandbox project, occasional out-of-sync state can be resolved with a refresh.

Beware Impure Rendering

Because browsers cache images they have already downloaded, the demo modifies URLs with a cache buster to keep repeated runs consistent.

const [cacheBuster, setCacheBuster] = useState(INITIAL_TIME);


const { data } = useSuspenseQuery(GET_IMAGES_QUERY, { page });
const images = data.allBooks.Books.map(
  (b) => b.smallImage + `?cachebust=${cacheBuster}`
);

INITIAL_TIME is defined at module level:

const INITIAL_TIME = +new Date();

Doing this instead — computing the cache buster lazily inside the component — causes severe problems:

const [cacheBuster, setCacheBuster] = useState(+new Date());

On first render, images attempt to render and the cache causes a suspension; React cancels the render and shows the fallback. When the promises resolve, React re-attempts the initial render, re-running the useState initializer with a new value and producing an entirely new set of URLs, which suspend again, indefinitely. The component never completes rendering.

The broader lesson: rendering should be pure and free of side effects. React may re-attempt rendering any number of times, and given the same initial props, the same state must result.

Try the demo, or the network waterfall demo.