Skip to main content

useSrcLoader: Optimizing Responsive Images

Best Practices Guide for Image Loading & CDNs


Introduction

In modern web development, delivering the right image size to the right device is critical for performance and Core Web Vitals (LCP). The useSrcLoader hook provides a unified interface for generating responsive image URLs and media queries, abstracting away the complexities of different CDN providers.

How it works

  1. Input Parsing: The hook accepts a base src and an optional array of imgSizes.
  2. CDN Transformation: It uses the project's global configuration to append the correct width and quality parameters to each URL.
  3. Media Query Generation: It automatically constructs CSS media query strings based on minScreenWidth and maxScreenWidth parameters.
  4. Memoized Output: It returns a stable object containing the primary source and a list of srcMedia objects for use in <picture> elements.

Why use useSrcLoader?

  • Provider Agnostic: Switch between CDNs (Cloudinary, Imgix, Contentful, etc.) by changing a single configuration value without touching your component code.
  • Declarative Responsiveness: Define image sizes based on screen breakpoints directly in your component logic.
  • Simplified <picture> Syntax: Automates the generation of media and srcSet attributes.

See Also

For a detailed technical breakdown and additional implementation patterns, refer to the following resources:


Key Takeaways

  • Always use the <picture> element: For maximum browser compatibility and performance, map the srcMedia array to <source> tags within a <picture> element.
  • Define mobile-first breakpoints: Ensure your imgSizes cover smaller screens to prevent heavy desktop images from loading on mobile devices.
  • Leverage global quality settings: Avoid hardcoding quality in every hook call; rely on the global configuration for consistency across the site.
  • Use Custom Loaders sparingly: Only use the loader parameter for third-party images that are not hosted on your primary CDN.
  • Provide a fallback src: Always ensure the base src is a valid, high-quality image that can serve as a fallback if media queries don't match or the browser is legacy.