DEV Community

Cover image for Lazy loading image
Palash Gupta
Palash Gupta

Posted on

Lazy loading image

Have you ever wondered what type of magic shows in the platform like Medium to render the image

First, the image is blurred and after sometime image, the whole image is loaded

How this is happing ????

Two images are being rendered the first one with low-resolution but with the exact width and height of the original image, and in parallel, we are loading the original image with full resolution and when the images are loaded, the low-resolution image is replaced with the full resolution image

TADA...

but let's hold for a sec how we can achieve this one in code

import { useEffect, useState } from 'react'

const useLazyImage = (src: string): useLazyImageProps => {
  const [sourceLoaded, setSourceLoaded] = useState<string | null>(
    null,
  )
  const [loading, setLoading] = useState<boolean>(true)

  useEffect(() => {
    const img = new Image()
    img.src = src
    img.onload = () => {
      setLoading(false)
      setSourceLoaded(src)
    }

    return () => {
      img.remove()
    }
  }, [src])

  return {
    loading,
    src: sourceLoaded,
  }
}

interface useLazyImageProps {
  loading: boolean
  src: null | string
}

export default useLazyImage
Enter fullscreen mode Exit fullscreen mode

there are a hell of a lot of things that are going on here let go through one by one

useLazyImage is a hook that accepts the address of the full resolution image and returns the loading true/false and src

while mounting the component it creates the img element with the address of the image and when the image finishes it loading we set the loading to false via onLoad event and remove the img node on un-mounting the node.

is-it simple

Let me know down in the comments

Top comments (0)