
Company News
Socket Named Top Sales Organization by RepVue
Socket won two 2026 Reppy Awards from RepVue, ranking in the top 5% of all sales orgs. AE Alexandra Lister shares what it's like to grow a sales career here.
react-img-toolkit
Advanced tools
A lightweight React library for optimizing image loading through preloading, lazy loading, and caching capabilities
A lightweight React library for optimizing image loading through preloading, lazy loading, and caching capabilities.
npm install react-img-toolkit
import { ImagePreloader } from 'react-img-toolkit';
function Gallery() {
const data = {
images: [
'https://example.com/image1.jpg',
'https://example.com/image2.jpg',
],
otherData: 'Hello World!',
};
return (
<ImagePreloader
data={data}
onSuccess={() => console.log('All images loaded!')}
onError={(error) => console.error('Failed to load:', error)}
>
{/* Your gallery content */}
</ImagePreloader>
);
}
Preload multiple images and track their loading status. The onSuccess callback is executed only when there are uncached image URLs that need to be loaded. If all images are cached, the onSuccess callback does not run. This hook checks for browser caching before executing the onSuccess callback, ensuring it only runs when necessary. For example, if all images are cached, the onSuccess callback will not be executed, but if there are uncached images, the onSuccess callback will run after those images are loaded.
import { useImagePreloader } from 'react-img-toolkit';
function Gallery() {
const { imageUrls } = useImagePreloader({
data: [
'https://example.com/image1.jpg',
'https://example.com/image2.jpg'
],
onSuccess: () => console.log("All uncached images preloaded successfully"),
onError: (error) => console.error("Failed to preload images:", error),
});
return (
<div>
<p>Loaded {imageUrls.length} images</p>
{imageUrls.map((url, index) => (
<img key={index} src={url} alt={`Image ${index + 1}`} />
))}
</div>
);
}
Load images only when they enter the viewport:
import { useLazyImage } from 'react-img-toolkit';
function LazyImage() {
const { ref, isIntersecting, isLoaded } = useLazyImage({
src: 'https://example.com/large-image.jpg',
options: {
threshold: 0.5,
rootMargin: '200px',
}
});
return (
<div ref={ref}>
{isLoaded && (
<img src="https://example.com/large-image.jpg" alt="Lazy loaded" />
)}
</div>
);
}
Cache images for faster subsequent loads:
import { useImageCache } from 'react-img-toolkit';
function CachedImage() {
const { cachedSrc, loading, isCached } = useImageCache({
src: 'https://example.com/image.jpg',
});
if (loading) return <div>Loading...</div>;
return <img src={cachedSrc} alt="Cached image" />;
}
The useImageLoad hook is particularly useful when you need direct access to the DOM image element, such as when working with canvas or WebGL. It provides:
Load images with custom configurations, particularly useful for canvas applications:
import { useImageLoad } from 'react-img-toolkit';
function CanvasImage() {
const { image, isLoading, error } = useImageLoad({
url: 'https://example.com/image.jpg',
crossOrigin: 'anonymous',
referrerPolicy: 'no-referrer'
});
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<canvas
ref={canvasRef => {
if (canvasRef && image) {
const ctx = canvasRef.getContext('2d');
if (ctx) {
canvasRef.width = image.width;
canvasRef.height = image.height;
ctx.drawImage(image, 0, 0);
}
}
}}
/>
</div>
);
}
Track the loading status of an image:
import { useImageStatus } from 'react-img-toolkit';
function ImageWithStatus() {
const status = useImageStatus({ src: 'https://example.com/image.jpg' });
return (
<div>
<p>Status: {status}</p>
{status === 'loaded' && <img src="https://example.com/image.jpg" alt="Loaded" />}
</div>
);
}
The useImageOptimizer hook is designed to optimize images by resizing, adjusting quality, and applying transformations such as rotation and flipping. It manages loading states and errors during the optimization process.
Image Resizing:
Quality Control:
Format Handling:
Transformations:
Transparency Management:
Asynchronous Processing:
FileReader to load images and a canvas element for the optimization process, ensuring efficient handling of image data.Error Management:
Here’s a simple example of how to use useImageOptimizer:
import { useImageOptimizer } from 'react-img-toolkit';
function ImageOptimizerComponent() {
const { optimizeImage, loading, error } = useImageOptimizer();
const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (file) {
const options = { maxWidth: 800, maxHeight: 600, quality: 0.8, rotate: 90 };
const optimizedBlob = await optimizeImage(file, options);
// Handle the optimized image blob (e.g., display it, upload it, etc.)
}
};
return (
<div>
<input type="file" onChange={handleFileChange} />
{loading && <p>Loading...</p>}
{error && <p>Error: {error}</p>}
</div>
);
}
The useImageConverter hook provides a way to convert images between different formats while managing loading states and errors. It supports various options for customization during the conversion process.
Format Support:
Quality Control:
Transparency Handling:
Asynchronous Processing:
FileReader to load images and a canvas element for the conversion process, ensuring efficient handling of image data.Error Management:
Here’s a simple example of how to use useImageConverter:
import { useImageConverter } from 'react-img-toolkit';
function ImageConverterComponent() {
const { convertImage, loading, error } = useImageConverter();
const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (file) {
const options = { format: 'image/webp', quality: 0.8, keepTransparency: true };
const convertedBlob = await convertImage(file, options);
// Handle the converted image blob (e.g., display it, upload it, etc.)
}
};
return (
<div>
<input type="file" onChange={handleFileChange} />
{loading && <p>Loading...</p>}
{error && <p>Error: {error}</p>}
</div>
);
}
The useImageOptimizer hook is designed to optimize images by resizing, adjusting quality, and applying transformations such as rotation and flipping. It manages loading states and errors during the optimization process.
Image Resizing:
Quality Control:
Format Handling:
Transformations:
Transparency Management:
Asynchronous Processing:
FileReader to load images and a canvas element for the optimization process, ensuring efficient handling of image data.Error Management:
Here’s a simple example of how to use useImageOptimizer:
import { useImageOptimizer } from 'react-img-toolkit';
function ImageOptimizerComponent() {
const { optimizeImage, loading, error } = useImageOptimizer();
const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (file) {
const options = { maxWidth: 800, maxHeight: 600, quality: 0.8, rotate: 90 };
const optimizedBlob = await optimizeImage(file, options);
// Handle the optimized image blob (e.g., display it, upload it, etc.)
}
};
return (
<div>
<input type="file" onChange={handleFileChange} />
{loading && <p>Loading...</p>}
{error && <p>Error: {error}</p>}
</div>
);
}
The useImageMeta hook extracts metadata from an image file, providing information such as dimensions, type, size, and name.
Key Features:
Usage Example:
import { useImageMeta } from 'react-img-toolkit';
function ImageUploader() {
const [file, setFile] = useState<File | null>(null);
const { metadata, error } = useImageMeta(file);
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const selectedFile = event.target.files?.[0];
if (selectedFile) {
setFile(selectedFile);
}
};
return (
<div>
<input type="file" onChange={handleFileChange} />
{error && <p>Error: {error}</p>}
{metadata && (
<div>
<p>Name: {metadata.name}</p>
<p>Type: {metadata.type}</p>
<p>Size: {metadata.size} bytes</p>
<p>Dimensions: {metadata.width} x {metadata.height}</p>
</div>
)}
</div>
);
}
| Prop | Type | Description |
|---|---|---|
| data | any | Any structured data. |
| onSuccess | () => void | Callback when all images are loaded |
| onError | (error: Error) => void | Callback when an error occurs |
| children | ReactNode | Content to render |
interface ImagePreloaderProps {
data?: any; // Any data to extract URLs from
onSuccess?: () => void; // Callback on successful preload
onError?: (error: Error) => void; // Callback on preload error
children: React.ReactNode; // Child components to render
}
interface ImagePreloaderState {
imageUrls: string[];
count: number;
}
function useImagePreloader({
data = {},
onSuccess,
onError,
}: UseImagePreloaderProps = {}): ImagePreloaderState;
interface UseLazyImageProps {
src: string;
options?: {
threshold?: number;
rootMargin?: string;
};
}
interface UseLazyImageResult {
ref: RefObject<HTMLElement>;
isIntersecting: boolean;
isLoaded: boolean;
}
function useLazyImage({
src,
options,
}: UseLazyImageProps): UseLazyImageResult;
interface UseImageCacheProps {
src: string;
}
interface UseImageCacheResult {
cachedSrc: string | null;
loading: boolean;
isCached: boolean;
}
function useImageCache({ src }: UseImageCacheProps): UseImageCacheResult;
interface UseImageLoadProps {
url: string;
crossOrigin?: HTMLImageElement['crossOrigin'];
referrerPolicy?: HTMLImageElement['referrerPolicy'];
}
interface UseImageLoadResult {
image: HTMLImageElement | null;
isLoading: boolean;
error: Error | null;
}
function useImageLoad(
{
url,
crossOrigin,
referrerPolicy
}: UseImageLoadProps
): UseImageLoadResult;
interface UseImageStatusProps {
src: string;
}
interface UseImageStatusResult {
status: 'idle' | 'loading' | 'loaded' | 'error';
}
function useImageStatus(
{ src }: UseImageStatusProps
): UseImageStatusResult;
interface UseImageConverterProps {
src: string;
format: string;
}
interface UseImageConverterResult {
convert: string | null;
status: 'idle' | 'loading' | 'loaded' | 'error';
}
function useImageConverter(
{ src, format }: UseImageConverterProps
): UseImageConverterResult;
interface UseImageOptimizerProps {
maxWidth?: number;
maxHeight?: number;
quality?: number;
rotate?: number;
flipHorizontally?: boolean;
flipVertically?: boolean;
}
interface UseImageOptimizerResult {
optimizeImage: (file: File, options: UseImageOptimizerProps) => Promise<Blob | null>;
loading: boolean;
error: Error | null;
}
function useImageOptimizer(): UseImageOptimizerResult;
interface UseImageMetaProps {
file: File | null; // The image file to extract metadata from
}
interface UseImageMetaResult {
metadata: {
width: number;
height: number;
type: string;
size: number;
name: string;
} | null; // Image metadata or null if not available
error: string | null; // Error message if any error occurs
}
function useImageMeta(file: UseImageMetaProps): UseImageMetaResult;
git clone https://github.com/IxtiyorDeveloper/react-img-toolkit.git
cd react-img-toolkit
npm install
npm run dev
npm test
Contributions are welcome! Please feel free to submit a Pull Request.
MIT
FAQs
A lightweight React library for optimizing image loading through preloading, lazy loading, and caching capabilities
We found that react-img-toolkit demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Company News
Socket won two 2026 Reppy Awards from RepVue, ranking in the top 5% of all sales orgs. AE Alexandra Lister shares what it's like to grow a sales career here.

Security News
NIST will stop enriching most CVEs under a new risk-based model, narrowing the NVD's scope as vulnerability submissions continue to surge.

Company News
/Security News
Socket is an initial recipient of OpenAI's Cybersecurity Grant Program, which commits $10M in API credits to defenders securing open source software.