@resilient

useAdaptiveImage

Automatically select the optimal image quality based on network conditions.

Live Demo

Status

Online

Connection

Unknown

Speed

N/A

Selected: High Quality (600px)
Adaptive quality image
600px

How to test

Open DevTools → Network tab → Throttle to "Slow 3G" or "Fast 3G" and refresh. The hook will select a lower resolution image to save bandwidth.

Installation

npm install react-resilient-hooks

Usage

import { useAdaptiveImage } from 'react-resilient-hooks';

const imageSources = {
  low: 'https://example.com/image-150.jpg',
  medium: 'https://example.com/image-300.jpg',
  high: 'https://example.com/image-600.jpg',
};

function MyComponent() {
  const { src, quality } = useAdaptiveImage(imageSources);

  return (
    <div>
      <img src={src} alt="Adaptive image" />
      <p>Current quality: {quality}</p>
    </div>
  );
}

API

Parameters

sources{ low: string, medium?: string, high: string }

Object containing URLs for different image qualities.

options?AdaptiveImageOptions

Optional configuration object.

Options

ssrDefault?'low' | 'medium' | 'high'

Default quality to use during SSR. Defaults to 'high'.

thresholds?{ low: number, medium: number }

Custom downlink thresholds (Mbps). Defaults to { low: 0.5, medium: 1.5 }.

Returns

srcstring

The URL of the selected image based on current network conditions.

quality'low' | 'medium' | 'high'

The quality level that was selected.

How It Works

The hook uses the Network Information API to detect the effective connection type:

  • 4G / WiFi: Returns the high-quality image
  • 3G: Returns the medium-quality image
  • 2G / Slow 2G: Returns the low-quality image

This helps reduce data usage and improve load times for users on slower connections.