Installations
npm install react-img-toolkit
Developer Guide
Typescript
Yes
Module System
CommonJS
Node Version
20.16.0
NPM Version
10.9.0
Score
66
Supply Chain
94.2
Quality
90.5
Maintenance
100
Vulnerability
99.6
License
Releases
Unable to fetch releases
Contributors
Unable to fetch Contributors
Languages
TypeScript (93.2%)
CSS (4.08%)
JavaScript (1.79%)
HTML (0.93%)
Love this project? Help keep it running — sponsor us today! 🚀
Developer
IxtiyorDeveloper
Download Statistics
Total Downloads
757
Last Day
4
Last Week
61
Last Month
757
Last Year
757
GitHub Statistics
MIT License
1 Stars
27 Commits
1 Watchers
2 Branches
1 Contributors
Updated on Feb 05, 2025
Bundle Size
7.95 kB
Minified
2.57 kB
Minified + Gzipped
Package Meta Information
Latest Version
1.0.9
Package Id
react-img-toolkit@1.0.9
Unpacked Size
65.04 kB
Size
11.32 kB
File Count
25
NPM Version
10.9.0
Node Version
20.16.0
Published on
Feb 05, 2025
Total Downloads
Cumulative downloads
Total Downloads
757
Last Day
-95.1%
4
Compared to previous day
Last Week
-75.2%
61
Compared to previous week
Last Month
0%
757
Compared to previous month
Last Year
0%
757
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
3
React Image Toolkit
A lightweight React library for optimizing image loading through preloading, lazy loading, and caching capabilities.
Features
- 🚀 Image Preloading: Load images in advance for instant display, especially useful when working with Electron.js since preloaded images will continue displaying even if the internet connection is lost.
- 🎯 Lazy Loading: Load images only when they enter the viewport
- 💾 Image Caching: Cache images for faster subsequent loads
- 📊 Status Tracking: Monitor image loading states
- 🎨 TypeScript Support: Full TypeScript support with type definitions
- 🪶 Lightweight: No external dependencies except React
- 🖼️ Custom Configurations: Supports cross-origin, referrer policies, and direct access to the HTMLImageElement for advanced use cases.
Installation
1npm install react-img-toolkit
Usage
Image Preloader Component
data can be any structured, ImagePreloader will extract image URLs from it.
1import { ImagePreloader } from 'react-img-toolkit'; 2 3function Gallery() { 4 const data = { 5 images: [ 6 'https://example.com/image1.jpg', 7 'https://example.com/image2.jpg', 8 ], 9 otherData: 'Hello World!', 10 }; 11 12 return ( 13 <ImagePreloader 14 data={data} 15 onSuccess={() => console.log('All images loaded!')} 16 onError={(error) => console.error('Failed to load:', error)} 17 > 18 {/* Your gallery content */} 19 </ImagePreloader> 20 ); 21}
Hooks
useImagePreloader
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.
1import { useImagePreloader } from 'react-img-toolkit'; 2 3function Gallery() { 4 const { imageUrls } = useImagePreloader({ 5 data: [ 6 'https://example.com/image1.jpg', 7 'https://example.com/image2.jpg' 8 ], 9 onSuccess: () => console.log("All uncached images preloaded successfully"), 10 onError: (error) => console.error("Failed to preload images:", error), 11 }); 12 13 return ( 14 <div> 15 <p>Loaded {imageUrls.length} images</p> 16 {imageUrls.map((url, index) => ( 17 <img key={index} src={url} alt={`Image ${index + 1}`} /> 18 ))} 19 </div> 20 ); 21}
useLazyImage
Load images only when they enter the viewport:
1import { useLazyImage } from 'react-img-toolkit';
2
3function LazyImage() {
4 const { ref, isIntersecting, isLoaded } = useLazyImage({
5 src: 'https://example.com/large-image.jpg',
6 options: {
7 threshold: 0.5,
8 rootMargin: '200px',
9 }
10 });
11
12 return (
13 <div ref={ref}>
14 {isLoaded && (
15 <img src="https://example.com/large-image.jpg" alt="Lazy loaded" />
16 )}
17 </div>
18 );
19}
useImageCache
Cache images for faster subsequent loads:
1import { useImageCache } from 'react-img-toolkit'; 2 3function CachedImage() { 4 const { cachedSrc, loading, isCached } = useImageCache({ 5 src: 'https://example.com/image.jpg', 6 }); 7 8 if (loading) return <div>Loading...</div>; 9 10 return <img src={cachedSrc} alt="Cached image" />; 11}
useImageLoad
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:
- Full control over image loading configuration
- Cross-origin resource sharing (CORS) settings
- Referrer policy configuration
- Direct access to the HTMLImageElement
- Loading state and error handling
Load images with custom configurations, particularly useful for canvas applications:
1import { useImageLoad } from 'react-img-toolkit'; 2 3function CanvasImage() { 4 const { image, isLoading, error } = useImageLoad({ 5 url: 'https://example.com/image.jpg', 6 crossOrigin: 'anonymous', 7 referrerPolicy: 'no-referrer' 8 }); 9 10 if (isLoading) return <div>Loading...</div>; 11 if (error) return <div>Error: {error.message}</div>; 12 13 return ( 14 <div> 15 <canvas 16 ref={canvasRef => { 17 if (canvasRef && image) { 18 const ctx = canvasRef.getContext('2d'); 19 if (ctx) { 20 canvasRef.width = image.width; 21 canvasRef.height = image.height; 22 ctx.drawImage(image, 0, 0); 23 } 24 } 25 }} 26 /> 27 </div> 28 ); 29}
useImageStatus
Track the loading status of an image:
1import { useImageStatus } from 'react-img-toolkit'; 2 3function ImageWithStatus() { 4 const status = useImageStatus({ src: 'https://example.com/image.jpg' }); 5 return ( 6 <div> 7 <p>Status: {status}</p> 8 {status === 'loaded' && <img src="https://example.com/image.jpg" alt="Loaded" />} 9 </div> 10 ); 11}
useImageOptimizer
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.
Key Features
-
Image Resizing:
- Allows you to specify maximum width and height, ensuring that images do not exceed these dimensions.
-
Quality Control:
- Supports adjustable quality settings for JPEG and WebP formats (from 0 to 1).
-
Format Handling:
- Detects the MIME type of the image if not specified, supporting formats like JPEG, PNG, WebP, and GIF.
-
Transformations:
- Provides options to rotate the image and flip it horizontally or vertically.
-
Transparency Management:
- Option to keep transparency for PNG and WebP formats, or remove it for JPEG and WebP if specified.
-
Asynchronous Processing:
- Utilizes a
FileReader
to load images and acanvas
element for the optimization process, ensuring efficient handling of image data.
- Utilizes a
-
Error Management:
- Provides error handling to capture and report issues during the optimization process.
Usage Example
Here’s a simple example of how to use useImageOptimizer
:
1import { useImageOptimizer } from 'react-img-toolkit'; 2 3function ImageOptimizerComponent() { 4 const { optimizeImage, loading, error } = useImageOptimizer(); 5 6 const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => { 7 const file = event.target.files?.[0]; 8 if (file) { 9 const options = { maxWidth: 800, maxHeight: 600, quality: 0.8, rotate: 90 }; 10 const optimizedBlob = await optimizeImage(file, options); 11 // Handle the optimized image blob (e.g., display it, upload it, etc.) 12 } 13 }; 14 15 return ( 16 <div> 17 <input type="file" onChange={handleFileChange} /> 18 {loading && <p>Loading...</p>} 19 {error && <p>Error: {error}</p>} 20 </div> 21 ); 22}
useImageConverter
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.
Key Features
-
Format Support:
- Converts images to the following formats: JPEG, PNG, WebP, and GIF.
-
Quality Control:
- Allows for adjustable quality settings for JPEG and WebP formats (from 0 to 1).
-
Transparency Handling:
- Option to keep transparency for PNG and WebP formats.
- Removes transparency for JPEG and WebP if specified.
-
Asynchronous Processing:
- Utilizes a
FileReader
to load images and acanvas
element for the conversion process, ensuring efficient handling of image data.
- Utilizes a
-
Error Management:
- Provides error handling to capture and report issues during the conversion process.
Usage Example
Here’s a simple example of how to use useImageConverter
:
1import { useImageConverter } from 'react-img-toolkit'; 2 3function ImageConverterComponent() { 4 const { convertImage, loading, error } = useImageConverter(); 5 6 const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => { 7 const file = event.target.files?.[0]; 8 if (file) { 9 const options = { format: 'image/webp', quality: 0.8, keepTransparency: true }; 10 const convertedBlob = await convertImage(file, options); 11 // Handle the converted image blob (e.g., display it, upload it, etc.) 12 } 13 }; 14 15 return ( 16 <div> 17 <input type="file" onChange={handleFileChange} /> 18 {loading && <p>Loading...</p>} 19 {error && <p>Error: {error}</p>} 20 </div> 21 ); 22}
useImageOptimizer
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.
Key Features
-
Image Resizing:
- Allows you to specify maximum width and height, ensuring that images do not exceed these dimensions.
-
Quality Control:
- Supports adjustable quality settings for JPEG and WebP formats (from 0 to 1).
-
Format Handling:
- Detects the MIME type of the image if not specified, supporting formats like JPEG, PNG, WebP, and GIF.
-
Transformations:
- Provides options to rotate the image and flip it horizontally or vertically.
-
Transparency Management:
- Option to keep transparency for PNG and WebP formats, or remove it for JPEG and WebP if specified.
-
Asynchronous Processing:
- Utilizes a
FileReader
to load images and acanvas
element for the optimization process, ensuring efficient handling of image data.
- Utilizes a
-
Error Management:
- Provides error handling to capture and report issues during the optimization process.
Usage Example
Here’s a simple example of how to use useImageOptimizer
:
1import { useImageOptimizer } from 'react-img-toolkit'; 2 3function ImageOptimizerComponent() { 4 const { optimizeImage, loading, error } = useImageOptimizer(); 5 6 const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => { 7 const file = event.target.files?.[0]; 8 if (file) { 9 const options = { maxWidth: 800, maxHeight: 600, quality: 0.8, rotate: 90 }; 10 const optimizedBlob = await optimizeImage(file, options); 11 // Handle the optimized image blob (e.g., display it, upload it, etc.) 12 } 13 }; 14 15 return ( 16 <div> 17 <input type="file" onChange={handleFileChange} /> 18 {loading && <p>Loading...</p>} 19 {error && <p>Error: {error}</p>} 20 </div> 21 ); 22}
useImageMeta
The useImageMeta
hook extracts metadata from an image file, providing information such as dimensions, type, size, and name.
Key Features:
- Metadata Extraction: Retrieves width, height, type, size, and name of the image.
- Error Handling: Captures errors during file reading and image loading.
- State Management: Uses React's state to manage metadata and error states.
Usage Example:
1import { useImageMeta } from 'react-img-toolkit'; 2 3function ImageUploader() { 4 const [file, setFile] = useState<File | null>(null); 5 const { metadata, error } = useImageMeta(file); 6 7 const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => { 8 const selectedFile = event.target.files?.[0]; 9 if (selectedFile) { 10 setFile(selectedFile); 11 } 12 }; 13 14 return ( 15 <div> 16 <input type="file" onChange={handleFileChange} /> 17 {error && <p>Error: {error}</p>} 18 {metadata && ( 19 <div> 20 <p>Name: {metadata.name}</p> 21 <p>Type: {metadata.type}</p> 22 <p>Size: {metadata.size} bytes</p> 23 <p>Dimensions: {metadata.width} x {metadata.height}</p> 24 </div> 25 )} 26 </div> 27 ); 28}
API Reference
ImagePreloader Component
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 |
useImagePreloader Hook
1 2interface ImagePreloaderProps { 3 data?: any; // Any data to extract URLs from 4 onSuccess?: () => void; // Callback on successful preload 5 onError?: (error: Error) => void; // Callback on preload error 6 children: React.ReactNode; // Child components to render 7} 8 9interface ImagePreloaderState { 10 imageUrls: string[]; 11 count: number; 12} 13 14function useImagePreloader({ 15 data = {}, 16 onSuccess, 17 onError, 18 }: UseImagePreloaderProps = {}): ImagePreloaderState;
useLazyImage Hook
1interface UseLazyImageProps { 2 src: string; 3 options?: { 4 threshold?: number; 5 rootMargin?: string; 6 }; 7} 8 9interface UseLazyImageResult { 10 ref: RefObject<HTMLElement>; 11 isIntersecting: boolean; 12 isLoaded: boolean; 13} 14 15function useLazyImage({ 16 src, 17 options, 18}: UseLazyImageProps): UseLazyImageResult;
useImageCache Hook
1interface UseImageCacheProps { 2 src: string; 3} 4 5interface UseImageCacheResult { 6 cachedSrc: string | null; 7 loading: boolean; 8 isCached: boolean; 9} 10function useImageCache({ src }: UseImageCacheProps): UseImageCacheResult;
useImageLoad Hook
1interface UseImageLoadProps { 2 url: string; 3 crossOrigin?: HTMLImageElement['crossOrigin']; 4 referrerPolicy?: HTMLImageElement['referrerPolicy']; 5} 6 7interface UseImageLoadResult { 8 image: HTMLImageElement | null; 9 isLoading: boolean; 10 error: Error | null; 11} 12 13function useImageLoad( 14{ 15 url, 16 crossOrigin, 17 referrerPolicy 18}: UseImageLoadProps 19): UseImageLoadResult;
useImageStatus Hook
1interface UseImageStatusProps { 2 src: string; 3} 4 5interface UseImageStatusResult { 6 status: 'idle' | 'loading' | 'loaded' | 'error'; 7} 8 9function useImageStatus( 10 { src }: UseImageStatusProps 11): UseImageStatusResult;
useImageConverter Hook
1interface UseImageConverterProps { 2 src: string; 3 format: string; 4} 5 6interface UseImageConverterResult { 7 convert: string | null; 8 status: 'idle' | 'loading' | 'loaded' | 'error'; 9} 10 11function useImageConverter( 12 { src, format }: UseImageConverterProps 13): UseImageConverterResult;
useImageOptimizer Hook
1interface UseImageOptimizerProps { 2 maxWidth?: number; 3 maxHeight?: number; 4 quality?: number; 5 rotate?: number; 6 flipHorizontally?: boolean; 7 flipVertically?: boolean; 8} 9 10interface UseImageOptimizerResult { 11 optimizeImage: (file: File, options: UseImageOptimizerProps) => Promise<Blob | null>; 12 loading: boolean; 13 error: Error | null; 14} 15 16function useImageOptimizer(): UseImageOptimizerResult;
useImageMeta Hook
1interface UseImageMetaProps { 2 file: File | null; // The image file to extract metadata from 3} 4 5interface UseImageMetaResult { 6 metadata: { 7 width: number; 8 height: number; 9 type: string; 10 size: number; 11 name: string; 12 } | null; // Image metadata or null if not available 13 error: string | null; // Error message if any error occurs 14} 15 16function useImageMeta(file: UseImageMetaProps): UseImageMetaResult;
Development
- Clone the repository:
1git clone https://github.com/IxtiyorDeveloper/react-img-toolkit.git 2cd react-img-toolkit
- Install dependencies:
1npm install
- Start development server:
1npm run dev
- Run tests:
1npm test
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
MIT

No vulnerabilities found.

No security vulnerabilities found.
Other packages similar to react-img-toolkit
@codesandbox/sandpack-react
<img style="width:100%" src="https://user-images.githubusercontent.com/4838076/143581035-ebee5ba2-9cb1-4fe8-a05b-2f44bd69bb4b.gif" alt="Component toolkit for live running code editing experiences" />
@abilovelchin/react-ts-starter-kit
<a href="https://github.com/abilovelchin/react-ts-starter-kit?sponsor=1"> <img src="https://img.shields.io/badge/-GitHub-%23555.svg?logo=github-sponsors" height="20"> </a> <a href="https://github.com/abilovelchin/react-ts-starter-kit"> <img src="https:/
@taktikorg/unde-animi-omnis
<p align="center"> <a href="https://www.npmjs.com/package/@taktikorg/unde-animi-omnis"><img src="https://img.shields.io/npm/v/@taktikorg/unde-animi-omnis"></a> <a href=""><img src="https://img.shields.io/github/actions/workflow/status/RemiMyrset/@taktikor
infocharts
<img src="https://raw.githubusercontent.com/garethslinn/public_infocharts/refs/heads/main/logo.svg" />