DEV Community

Ashutosh Sarangi
Ashutosh Sarangi

Posted on • Edited on

Image Optimization in Any Web Apps / Mobile Apps

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

Top comments (16)

Collapse
 
anmolbaranwal profile image
Anmol Baranwal

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

Collapse
 
ashutoshsarangi profile image
Ashutosh Sarangi

Very Nice, Thanks for sharing.

Collapse
 
efpage profile image
Eckehard

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.

Collapse
 
ashutoshsarangi profile image
Ashutosh Sarangi
  • 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.

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
ashutoshsarangi profile image
Ashutosh Sarangi

This we can add, to the above list.

Collapse
 
manonbox profile image
Oli

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?

Collapse
 
ashutoshsarangi profile image
Ashutosh Sarangi

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.

Collapse
 
roshan_khan_28 profile image
roshan khan

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

Collapse
 
martinbaun profile image
Martin Baun

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.

Collapse
 
topeogunleye profile image
topeogunleye

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

Collapse
 
ashutoshsarangi profile image
Ashutosh Sarangi

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.

Collapse
 
topeogunleye profile image
topeogunleye

Thanks again @ashutoshsarangi, that's nice to know

Collapse
 
abhinowww profile image
Abhinav Anand

nice article

Collapse
 
tatanka profile image
Tatanka.nl

Great!