Loading content…
Loading content…
Implement an image lazy loading and performance auditing component in React. Demonstrate how to defer off-screen images using browser Intersection Observer APIs, rendering low-res placeholders during loading.
Expected Output
A React Image component deferring source loading until elements cross viewport intersections.
Click to toggle the recommended code solution
Architectural Explanation
The component loads images using IntersectionObserver, falling back to lazy sources. It detaches observers on mounts and displays blurred low-res placeholders to avoid layout shifts.Code Snippet
import React, { useState, useEffect, useRef } from "react";
export function LazyImage({ src, alt, placeholderSrc }: { src: string; alt: string; placeholderSrc: string }) {
const [isLoaded, setIsLoaded] = useState(false);
const [currSrc, setCurrSrc] = useState(placeholderSrc);
const imgRef = useRef<HTMLImageElement>(null);
useEffect(() => {
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
setCurrSrc(src);
observer.disconnect();
}
});
}, { rootMargin: "100px" });
if (imgRef.current) {
observer.observe(imgRef.current);
}
return () => {
observer.disconnect();
};
}, [src]);
return (
<img
ref={imgRef}
src={currSrc}
alt={alt}
onLoad={() => { if (currSrc === src) setIsLoaded(true); }}
className={`transition-opacity duration-300 ${isLoaded ? "opacity-100" : "opacity-50 blur-sm"}`}
/>
);
}How to pitch this solution during technical interviews
I optimize page speeds by lazy loading off-screen assets. I register IntersectionObserver APIs on placeholder bounds, loading high-res sources only when images approach the viewport to reduce initial payloads.