Creating a modern image gallery with React Suspense

How the React Suspense API lets us create a seamless image gallery adaptable for uncertain network conditions

Note: At the time of this writing, according to the official React documentation, the technique laid out in this tutorial is still in beta and is not recommended to be used in production, however React is planning to change this in the upcoming releases.

What is React Suspense?

Basically what Suspense does is provide a fallback component, which is shown while the data is being loaded in the background. This way we do not need to provide a separate state variable to be able to show a temporary loader, while the async task is happening. This is especially useful when using stateless components.

The roadmap

The end result

This can be accomplished by utilising the react-cache package, which is built by the React team. It provides a simple caching solution for asynchronous tasks. Leveraging this package with the previously mentioned React Suspense API will give us the desired result.

Fetching images for the project

Step 1: Building the image component using react-cache

Step 2: Building the image wrapper using Suspense

Notice in the code above, that there can be three possible scenarios when preloading this image, based on the network speed and content delivery speed:

  1. If the network is really really slow, and the component is unable to preload even a low resolution image fast enough, we should show a preloading element.
  2. Once the low resolution image is loaded, it is rendered above the preloading element, and we now see a blurry version of the final image, which is essentially just a lower resolution of it combined with a css blur filter property.
  3. The high resolution image is loaded, and is now replaced by the low resolution one.

We now have a fully functional React Suspense API driven image component, that is capable of delivering a fast callback solution to asynchronous lazy loading for users with slower network speeds.

Step 3: Wrapping all up

Success! We now have a lazy loading image gallery that provides a pleasant user experience regardless of the user’s network speed.

The full example

A full-stack web developer and a videographer who does a bit of web design and photography.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store