Background 📜

Have you ever visited the homepage of a website and came across a situation where the high resolution images are taking forever to load?

During development, it is not always possible to load your high resolution images almost instantly. However, you can always work on generating an intuitive placeholder while those images are loading in the background of your webpage.

Loading images with BlurHash can be a useful technique to generate interactive and user-friendly image placeholders for your website whenever it is required.

Introduction 🏁

In this post, you are going to learn how to use BlurHash in your React application. As a third-party package, BlurHash provides a user-friendly and interactive representation of an image placeholder which visualises as a blurry view of your original website image.

Prerequisites 🚨

Before you proceed further with this post, you are advised to have a basic understanding of the following topics:

  • React
  • TypeScript
  • Yarn (package manager)

Table of Contents 🗒️

  • What is BlurHash?
  • Project Overview
  • Steps to Setup React with Vite
  • Implement Image list with React
  • Create an Image component with BlurHash
  • Wrapping Up

What is BlurHash? 💭

According to their documentation,

BlurHash is a compact representation of a placeholder for a given image.

To elaborate, BlurHash is an image placeholder algorithm that generates a special string of 30-40 characters (also known as BlurHash string) against a given image.

This string is generated on the backend of your application. On the client side of your application, we send the string as a JSON object property alongside the original image link.

The application's client side uses this string and decodes it to an image. The decoded image continues serving as a placeholder image until your original image finishes loading.

Project Overview 🎥

In this post, we will create a simple React application loading a list of images using BlurHash.

The final view of our application has been demonstrated below.

Lazy load images with React and BlurHash

Steps to Setup React with Vite 🛠️

  • To scaffold a project, run the following command in your terminal
yarn create vite 
  • Name our project folder as react-blurhash

Set project name as react-blurhash

  • Select React as our framework

Select React as framework

  • Select TypeScript as our variant

Select JavaScript as variant

  • Move to the folder directory react-blurhash
cd react-blurhash 
  • Install the essential dependencies by running
yarn 
  • Install the dependencies for using BlurHash
yarn add react-blurhash blurhash 
  • Install additional dependencies for using sass and classnames
yarn add sass classnames 
  • Run your local development server using
yarn dev 
  • Visit your localhost url as shown below

  • If you visit the localhost url, you see a page like this

If you have made it this far, then Congralutations!

You have successfully setup your project in your local environment

N.B. Using an IDE of your preference, open the source code and replace the .css file extensions with .scss for using SASS

Implement Image list with React 🔨

We will create a new file named imageList.jsx under src folder and populate it with an array of dummy image links from unsplash.com

 type ImageListItemType = { id: number, imageUrl: string, blurhashString: string } const ImageList: ImageListItemType[] = [ { id: 1, imageUrl: 'https://images.unsplash.com/photo-1666993804910-60191605094f', blurHashString: 'UXFrbUI=WVs-7%%2oLWB_4R+R+bHpJofs:s;', }, { id: 2, imageUrl: 'https://images.unsplash.com/photo-1666869391780-a3aa24cbfe91', blurHashString: 'U24.MK~qaKNG~q?bn%t74n9ZoL-;004nIUoL', }, { id: 3, imageUrl: 'https://images.unsplash.com/photo-1573068666708-ea84ee632e04', blurHashString: 'U~GJsv%Mt7ju*0ofofj[kqRiRjbHNGR*WBkC', }, ... ] export default ImageList 

You will notice for the code above that each object inside the ImageList array has a property called blurHashString.

This property contains the special string that is generated against the original image link

In the real world application, the BlurHash string should be generated for the given image link from the backend of your application.

For this simple project, we have manually generated the blurhashString property for each image by using their online BlurHash string generator from their documentation link

We will create a new folder src/components. Inside that folder, we will create our component named Image.tsx

Inside the Image component, we will create our image container with the <img> tag inside

const Image = ({ url } : ImageType) => ( <div className="images-list__container"> <img className="images-list__image" src={url} loading="lazy" /> </div> ); export default Image; 

We will import the imageList.ts file as well as the Image component in src/App.tsx

import ImageList from './imageList'; import Image from './components/Image' 

We will remove the boilerplate code existing inside the App component and map the data inside the imageList array with the Image component.

import ImageList from "./imageList"; import Image from "./components/Image"; import "./App.scss"; const App = () => ( <div className="images-list"> {ImageList.map(({id, imageUrl}) => ( <Image key={id} url={imageUrl} /> ))} </div> ); export default App; 

Let us style our view by editing the default css in src/App.scss

.images-list { display: flex; justify-content: center; flex-wrap: wrap; &__container { position: relative; width: 25%; height: 500px; margin: 10px; } &__image { position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; transition: opacity 0.2s 0.2s ease-out; border-radius: 10px; &--hidden { opacity: 0; } } } 

Delete the file src/index.scss and remove the following line of code in src/main.tsx

import './index.scss' 

Now, when you visit your localhost url, you will see a list of images like this

Why do we need an interactive image placeholder?

If we load our localhost url with high resolution images, we might see empty white spaces while our images are loading over the network.

Let us demonstrate this by using our browser's devTools and disabling browser cache.

In our browser's devTools, select the Network tab and tick Disable Cache

While keeping our browser's devTools open, reload the localhost url.

This will load the high resolution images in a slow and sluggish manner

If you had to load around hundreds of images like that on a single page, could you imagine the impression it would have left on your viewers?

The user experience of your website would be doomed and you would have lost potential audience in the long run.

With a user-friendly image placeholder, you can replace those white annoying empty spaces with something more meaningful and retain your website viewers.

This is where BlurHash can help you out.

Create an Image component with BlurHash 🔨

Let us create another component similar to the Image component in src/components and name it as ImageWithBlurhash

In ImageWithBlurhash, import the necessary React hooks

 import { useState, useEffect } from 'react'; 

Import the BlurhashCanvas component from react-blurhash for transforming our image's blurHashString to an image placeholder

import { BlurhashCanvas } from 'react-blurhash'; 

Import classnames function from classnames library for toggling class names based on a state inside the component

import classnames from 'classnames'; 

Create the component named LazyLoadImageWithBlurhash with the props hash and url.

import {FC} from 'react' interface ImageWithBlurhashProps { hash: string, url: string } const ImageWithBlurhash: FC<ImageWithBlurhashProps> = ({ hash, url }) => ( <div className="images-list__container"> <BlurhashCanvas hash={hash} style={{ width: "100%", height: "100%", borderRadius: "10px", }} punch={1} /> <img className="images-list__image" src={url} loading="lazy" /> </div> ); 

Let us understand what we have written for the code above.

The prop hash is the hashString that we have generated for the original image link. This hashString will be used as a prop for the BlurhashCanvas component.

The prop url refers the image's original link that will be used inside the src attribute of the img tag.

The BlurhashCanvas component generates a blurry preview of the original image while it keeps loading over the network.

The style prop in BlurhashCanvas has in-line css styles written for positioning and resizing the canvas tag.

The punch prop in BlurhashCanvas controls the contrast of the blurhash decoding algorithm. For further details, please checkout their react-blurhash's open source repository link.

On the next step, create a state named imageHasLoaded

const [imageHasLoaded, setImageHasLoaded] = useState<boolean>(false) 

We will use the classNames along with imageHasLoaded state to toggle a certain classname depending on the original image's loading state.

Let us add additional attributes to our img tag

 <img onLoad={() => { setImageHasLoaded(true); }} className={classnames("images-list__image", { "images-list__image--hidden": !imageHasLoaded, })} src={url} loading="lazy" /> 

The img tag will not be visible until the original image has fully loaded.

Once the image has fully loaded, the event onLoad will be triggered. This will set the imageHasLoaded state as false and will make the original image visible.

Go to src/App.js, and import ImageWithBlurhash

import ImageWithBlurhash from './components/ImageWithBlurhash'; 

Replace Image component with ImageWithBlurhash and use the prop hash to pass the blurHashString value of each image to the new component.

 const App = () => ( <div className="images-list"> {ImagesList.map((image) => ( <LazyLoadImageWithBlurhash key={image.id} hash={image.blurHashString} url={image.imageUrl} /> ))} </div> ); 

Let us go one step further and work on removing the image placeholders once the respective images have finished loading.

Go to src/componnents and open ImageWithBlurhash.jsx.

Inside the ImageWithBlurhash component, create a state named removeCanvas.

const [removeCanvas, setRemoveCanvas] = useState(false) 

Use the useEffect hook to write the following piece of code

useEffect(() => { let removeCanvasTimeout; if (imageHasLoaded) { removeCanvasTimeout = setTimeout(() => { setRemoveCanvas(true); }, 2000); } if (removeCanvasTimeout) { clearTimeout(removeCanvasTimeout); } }, [imageHasLoaded]) 

For the code above, we have used a variable called removeCanvasTimeout and assigned a timeout function to it to remove the canvas once an image has finished loading.

We have also made sure to remove the timeout while unmounting the ImageWithBlurhash component.

On the next step, we will render the BlurhashCanvas based on the state of removeCanvas

 {!removeCanvas && ( <BlurhashCanvas hash={hash} style={{ width: '100%', height: '100%', borderRadius: '10px', }} punch={1} /> )} 

Let us view the changes we have made till now.

We can see that for each image a blurry preview will be visible until the original image has finished loading.

Pat your yourself on the back if you have made it so far

You have successfully implemented React with BlurHash with this simple application.

If you find any discrepancy in the code, feel free to checkout the complete project code in the next section.

Source code

Project code

Wrapping Up

BlurHash is a simple and easy to use library that you can utilise into the client side of your web application to help you generate interactive image placeholders.

In my point of view, BlurHash has left a positive impression on me. I believe this library could be a better alternative to the other conventional methods of loading web images.

I hope I was able to help you understand how the library works and how you should implement it in your project.Thank you for taking your time to read this post.

Have a nice day!