Image Optimization in Any Web Apps / Mobile Apps
Ashutosh Sarangi

Ashutosh Sarangi @ashutoshsarangi

About: With 8 years in Front-End Dev, I'm skilled in JavaScript, React, Redux, and TypeScript. I'm passionate about learning and Sharing knowledge Let's grow together!

Location:
Limassole, Cyprus
Joined:
Jul 11, 2024

Image Optimization in Any Web Apps / Mobile Apps

Publish Date: Sep 2 '24
40 15

Advanced Image Optimization in React: Leveraging Intersection Observer

1. Existing Image Optimization with React Router

  • React Router has significantly improved image optimization. One of the key features is its ability to delay loading images that belong to components not yet rendered on the DOM.
  • This ensures that images or related API calls are not unnecessarily fetched until needed.
  • In React Router v6, you can further enhance this by using the action option to prefetch images when the user hovers over a route link.
  • This prefetching strategy allows images to load just in time for the user’s interaction, enhancing the perceived performance.

2. Enhanced Optimization with Intersection Observer

  • While React Router optimizes image loading by deferring it until necessary, there’s still room for improvement, especially regarding images outside the visible viewport at initial load.
  • Typically, when a page loads, the browser fetches all assets (images, CSS, JS) regardless of whether they are in the visible range, leading to unnecessary resource loading.

  • To avoid this, you can use the Intersection Observer API combined with React’s useState, useEffect, and useRef hooks.

  • This method allows you to delay loading images until they enter the viewport.

Here’s how it works:

  • Set up Intersection Observer: Monitor when an image enters the viewport.
  • Lazy Load Images: Use useState to manage the image's source and useEffect to trigger the image load only when it’s about to be visible.
  • Fixed Image Sizes: Ensure that image containers have predefined sizes. This prevents layout shifts and reduces CPU-intensive operations, which can otherwise negatively impact performance.

By implementing this strategy, the browser only loads images when they become visible to the user, reducing the initial page load time and improving the First Contentful Paint (FCP).

Addition Image Optimization technique

  1. use packages / tools to compress images
  2. Use srcSet and Sizes for responsive image designs

Git Hub repo for the Demo:-
https://github.com/Ashutoshsarangi/react-image-optimizer

Demo
Image description

Summary

  • Combining React Router’s deferred loading with Intersection Observer for lazy-loading images offers a powerful optimization strategy.
  • This approach not only enhances the user experience by speeding up initial load times but also ensures that resources are efficiently managed, particularly in image-heavy applications.

Adding Popular Comments which is also relevant

  1. loading= lazy from Oli
    https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/loading

  2. Image CDNS by Hossein Yazdi

Comments 15 total

  • roshan khan
    roshan khanSep 2, 2024

    the demo in this blog was really helpful. nice write!

  • Eckehard
    EckehardSep 2, 2024

    Even if you set the image size (which is truly recommended), this does not compress your source image. Images directly stored from camera usually have 1-2 MB, which can break any web page. Done right, a small image might be reduced to have 20 kB only, but therefore this image needs to be physically resized. It is most important that this is done before the image is sent over the internet, using the exact resolution they will have on page.

    But what to do, if you have a dynamic page which shows the image differently on different devices? CMS like Directus can resize your image on the fly, so you can retrieve any image in just the exact size the page needs. To reduce the server workload, reduced images are cached and can be delivered much faster the second time they are used in that exact resolution.

    • Ashutosh Sarangi
      Ashutosh SarangiSep 2, 2024
      • You can always use compressed images, as I mentioned the tools to do so in above article.
      • And in srcSet and sizes property when you mention different sizes and related view port based on the responsive viewport.
      • it will only download the relevant image. not all the image it will download

      srcset and size example from MDN

      Hope I clarify your queries, For more detail you can check the MDN link shared in the above article.

      Thank you for asking. I'm happy to help.

  • Anmol Baranwal
    Anmol BaranwalSep 2, 2024

    That is why I love Nextjs Image component.. it optimizes everything and there is a bot on GitHub: github.com/marketplace/imgbot .. that raise a PR with optimized images used in the codebase. It's free for public repos!

    Image description

  • topeogunleye
    topeogunleyeSep 3, 2024

    Hello @ashutoshsarangi, thank you so much for sharing, Image Optimization in Web Apps should help improve LCP scores.

    • Ashutosh Sarangi
      Ashutosh SarangiSep 3, 2024

      Thank you, Always happy to help.

      Yes, Not only LCP score, but it will off load the initial API calls, now with http1 we can hit around 6 parallel hits, after that we need to wait in queue.

      More detail article on HTTP is coming soon.

  • Abhinav Anand
    Abhinav AnandSep 3, 2024

    nice article

  • Tatanka.nl
    Tatanka.nlSep 3, 2024

    Great!

  • Oli
    OliSep 3, 2024

    Hey, why not use the built in img attribute loading="lazy" to defer loading of the image until it is close to the users view port? What are the advantages of doing this in JS?

    • Ashutosh Sarangi
      Ashutosh SarangiSep 3, 2024

      Yes, this also we can use, but as per the article with intersection Observer, you can have more flexibility around when you want to load, rather than Browser decide the appropriate time to load.

      But in General purpose we can useit. Nice Suggestion.

  • Martin Baun
    Martin BaunSep 3, 2024

    Generally, best practice is to serve up different sized images if they are displayed at different sizes even if they’re the same image. It’s annoying and tedious but worth it.

  • АнонимSep 4, 2024

    [deleted]

Add comment