Create a Medium like Lazy Image Loading Effect Using Gatsby.js in 5 minutes
Tags: gatsby, react, tutorial, webdev
Published: 2020-08-11 07:56:03

> Ensuring that users get the best experience with images on the web can be a tedious task. However, with Gatsby, we can leverage the power of [gatsby-image](https://www.gatsbyjs.org/packages/gatsby-image/) to get these speedy, optimised images with a little setup and a rich toolset.

You probably already saw this effect here on Medium, the blurry images with a nice “fade in” animation being changed by their respective originals. This effect is called Progressive/Lazy Image Loading.

## **What is Lazy Image Loading?**

Lazy Image Loading is a practice that’s been around for a decade and for good reason: images are usually the heaviest downloads on a given webpage and avoiding unloading images that are never seen saves the user bandwidth. With this technique, you can sharply load the images on your website when required, and use blurred placeholders while the original image is being lazy-loaded. And when it finishes loading, you can do a smooth transition to the original image. It’ll help you shave-off hours of work, use fewer resources, improve performance and build a meaningful experience for the user.

Gatsby does a great job optimizing images. With plugins and some configuration, you can setup image preloading and the blur-up effect in just a matter of minutes. This helps with a smoother user experience that is faster and way, way better!

## Let’s code right in!

### Step 1: Install Dependencies
> If you used the CLI, you’ll have to install these packages withyarn. If you used npm install, then continue to use npm so you don't mix the package installers. I'll be using npm for the rest of this demo.

To install [gatsby-image ](https://www.gatsbyjs.org/packages/gatsby-image/)with npm run:

npm install gatsby-image

We’ll also need to install two more npm packages that are required to process the images.

npm install gatsby-transformer-sharp gatsby-plugin-sharp
> You can read more about how these packages work, [here](https://www.gatsbyjs.org/packages/gatsby-transformer-sharp/).

### Step 2: Configure Gatsby

Once these packages are installed we need to include them manually in our gatsby-config.js file.

Include the following snippet to the file:

    module.exports = {
      siteMetadata: {
        title: 'Gatsby Default Starter'
      },
      plugins: [
        **{
          resolve: `gatsby-source-filesystem`,
          options: {
            path: `${__dirname}/src/images`,
            name: 'images'
          }
        },**
        {
          resolve: `gatsby-source-filesystem`,
          options: {
            name: `pages`,
            path: `${__dirname}/src/pages`,
          }
         },

        **'gatsby-transformer-sharp',
        'gatsby-plugin-sharp',
     **],
    }

This snippet will also allow us to create file nodes from our images that can be used later to query the /images folder inside the /src directory using GraphQL.

### Step 3: Writing queries in GraphQL

You can navigate to GraphiQL which is an integrated development environment (IDE). It’s a powerful (and all-around awesome) tool you’ll use often while building Gatsby websites.

You can access it when your site’s development server is running — normally at [http://localhost:8000/___graphql](http://GraphiQL is the GraphQL integrated development environment (IDE). It’s a powerful (and all-around awesome) tool you’ll use often while building Gatsby websites.  You can access it when your site’s development server is running—normally at http://localhost:8000/___graphql).

I have added 4 [images](https://www.dropbox.com/sh/xmvkmcronshzis0/AABanbmtca-8e9Ef0LcghAz-a?dl=0) inside my /src/images directory and I will write the following query to get the contents of the /images folder.

    {
      images: allFile {
        edges {
          node {
            relativePath
            name
            childImageSharp {
              fluid {
                srcSet
                src
                srcWebp
                base64
                originalImg
                originalName
                presentationHeight
                presentationWidth
                sizes
                srcSetWebp
                tracedSVG
                aspectRatio
              }
            }
          }
        }
      }
    }

Writing this query will return a string that you can see in the response column. This essentially means that Gatsby is able to find your image and process it.

![http://localhost:8000/__graphql](https://cdn-images-1.medium.com/max/3840/1*ZCNyJCaecfk-203XjIf0dA.png)*http://localhost:8000/__graphql*
> You can read more about how Gastby uses GraphQL [here](https://www.gatsbyjs.org/docs/graphql/).

### Step 4: Creating Components

Now that we have the query string, we can use it in our component. I will create a image.js component inside /src/components directory.
> Here, we need to import *StaticQuery* as well as *graphql* from *gatsby* and *Img *from *gatsby-image*.

    import { StaticQuery, graphql } from "gatsby"
    import Img from "gatsby-image"

We’ll now add the query that we made earlier to this component. Our React component should return a <StaticQuery> tag, which has a query property and a render property.

    <StaticQuery 
      query={
        graphql`{
          query {        
            images: allFile {
              edges {
                node {
                  relativePath
                  name
                  childImageSharp {
                    fluid {
                      ...GatsbyImageSharpFluid
                    }
                  }
                }
              }
            }
          }
      `} 
      render={(data) => (
        <>
          {*/* our JSX will go in here */*}
        </>
      )}
    />
> Notice how we are using [...GatsbyImageSharpFluid](https://www.gatsbyjs.org/docs/gatsby-image/#fluid-images) here, which is a fragment that replaces all the fields inside the fluid property.

Now, we need to include our image inside the render property which has to be passed down two props — a fluid and an alt prop.

The final result looks like this:

<iframe src="https://medium.com/media/62ca213dcd8db340e46de8c72a2b9de5" frameborder=0></iframe>

## We’re almost done!

Let’s create a new page that will accept these props to load the images.

### Step 5: Putting it together

I’ll name this pagegallery.js and place it in the/src/pages folder. And import the Image component we created earlier.

    import Image from "../components/Image"

Let’s pass down the props and here’s how our Gallery page should look like:

    *const* Gallery = () *=>* (
      <div>  
         <*Image* alt="image_1" filename="image_1.jpg" />
         <*Image* alt="image_2" filename="image_2.jpg" />
         <*Image* alt="image_3" filename="image_3.jpg" />
         <*Image* alt="image_4" filename="image_4.jpg" />
      </div>
    )

    export Gallery

It’s all done! Open up http://localhost:8000/gallery/ after running gatsby develop on your command line and…

![[https://gist.github.com/shrey-sachdeva2000/07a6b8ef822f2b385a15f186c933fcd6](https://gist.github.com/shrey-sachdeva2000/07a6b8ef822f2b385a15f186c933fcd6)](https://cdn-images-1.medium.com/max/2000/1*tOV6k1mvm1IJkGS67jY04w.gif)*[https://gist.github.com/shrey-sachdeva2000/07a6b8ef822f2b385a15f186c933fcd6](https://gist.github.com/shrey-sachdeva2000/07a6b8ef822f2b385a15f186c933fcd6)*

## ***Voila!***

There you have it. A really cool Lazy Loading Image Effect. Oh, by the way, I really wish I could lazy-load the image of the black hole too if only we had it in better pixels(a sincere astrophilia).

## Conclusion

Gatsby does a great job at processing and handling images and by leveraging the power of Gatsby, optimizing images is easy as pie. You can also try out generating a traced SVG of your image while it processes by applying a traceSVG argument and the appropriate [fragment](https://www.gatsbyjs.org/packages/gatsby-image/#fragments). Let me know how did that go for you!

**If you liked this article, don’t forget to give it a 👏 and share it with your friends! And subscribe for more geeky and cool articles in the future.**