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
, anduseRef
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 anduseEffect
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
- use packages / tools to compress images
- Use srcSet and Sizes for responsive image designs
Git Hub repo for the Demo:-
https://github.com/Ashutoshsarangi/react-image-optimizer
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
loading= lazy from Oli
https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/loadingImage CDNS by Hossein Yazdi
Top comments (16)
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!
Very Nice, Thanks for sharing.
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.
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.
This we can add, to the above list.
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?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.
the demo in this blog was really helpful. nice write!
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.
Hello @ashutoshsarangi, thank you so much for sharing, Image Optimization in Web Apps should help improve LCP scores.
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.
Thanks again @ashutoshsarangi, that's nice to know
nice article
Great!