tsx
import React, { useState, useCallback, useEffect } from 'react';
/**
* A performant, lazy-loading Image component that balances:
* - **Intrinsic sizing**: Uses provided `width`/`height` for CSS `aspect-ratio` to prevent layout shift.
* - **Priority hints**: `fetchPriority="high"` + dynamic `<link rel="preload">` for critical images.
* - **LQIP placeholders**: Optional base64 low-quality image placeholder with blur-up transition.
* - **Lazy by default**: `loading="lazy"` + `decoding="async"` for offscreen images.
* - Responsive: Supports `sizes` prop for `srcset`-like behavior (provide your own `srcset`).
* - Additional: Fade-in transition, error handling, ARIA accessibility.
*
* Usage:
* ```tsx
* <LazyImage
* src="/hero.jpg"
* width={1200}
* height={600}
* alt="Hero image"
* priority // Above-the-fold
* lqip="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD..." // Tiny base64 blur (e.g., 20x20px)
* sizes="(max-width: 768px) 100vw, 50vw"
* />
* ```
* Generate LQIP offline (e.g., via Sharp/Thumbor) for production perf.
*/
interface LazyImageProps {
src: string;
alt: string;
width: number; // Natural width (required for intrinsic sizing)
height: number; // Natural height (required for intrinsic sizing)
priority?: boolean;
lqip?: string; // Base64 LQIP (e.g., 10-20KB blurred low-res)
sizes?: string;
className?: string;
style?: React.CSSProperties;
}
export const LazyImage: React.FC<LazyImageProps> = ({
src,
alt,
width,
height,
priority = false,
lqip,
sizes = '100vw',
className = '',
style,
}) => {
const [loaded, setLoaded] = useState(false);
const [errored, setErrored] = useState(false);
const aspectRatio = `${width}/${height}`;
// Dynamic preload for priority images (avoids blocking render)
useEffect(() => {
if (priority) {
const link = document.createElement('link');
link.rel = 'preload';
link.fetchPriority = 'high';
link.as = 'image';
link.href = src;
link.sizes = sizes;
document.head.appendChild(link);
return () => {
document.head.removeChild(link);
};
}
}, [src, priority, sizes]);
const handleLoad = useCallback(() => {
setLoaded(true);
setErrored(false);
}, []);
const handleError = useCallback(() => {
setLoaded(true); // Hide placeholder on error
setErrored(true);
}, []);
return (
<div
className={className}
style={{
position: 'relative',
width: '100%',
aspectRatio,
overflow: 'hidden',
...style,
}}
role="img"
aria-label={alt}
>
{/* LQIP Placeholder */}
{lqip && (
<div
style={{
position: 'absolute',
inset: 0,
width: '100%',
height: '100%',
backgroundImage: `url(${lqip})`,
backgroundSize: 'cover',
backgroundPosition: 'center',
filter: `blur(20px) saturate(1.2)`,
transition: 'opacity 0.4s ease-in-out',
opacity: loaded ? 0 : 1,
pointerEvents: 'none',
}}
aria-hidden="true"
/>
)}
{/* Main Image */}
<img
src={src}
alt={alt}
loading={priority ? 'eager' : 'lazy'}
fetchPriority={priority ? 'high' : 'auto'}
decoding="async"
sizes={sizes}
width={width}
height={height}
style={{
position: 'absolute',
inset: 0,
width: '100%',
height: '100%',
objectFit: 'cover',
objectPosition: 'center',
opacity: loaded ? 1 : 0,
transition: 'opacity 0.4s ease-in-out',
pointerEvents: errored ? 'none' : 'auto',
}}
onLoad={handleLoad}
onError={handleError}
/>
{/* Error fallback (optional: customize with prop) */}
{errored && (
<div
style={{
position: 'absolute',
inset: 0,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
background: '#f0f0f0',
color: '#999',
fontSize: '14px',
pointerEvents: 'none',
}}
aria-hidden="true"
>
Image failed to load
</div>
)}
</div>
);
};