HooksuseImagePreload

useImagePreload

A React hook that monitors the loading state of an image.

Installation

npm install @madeinhaus/hooks

Import

import { useImagePreload } from '@madeinhaus/hooks';

Returns

  • loaded (boolean): A boolean indicating whether the image has been loaded.
  • fnRef (function): A callback ref that you pass to the image’s ref prop.
  • imgRef (Ref): A mutable ref object that holds the HTMLImageElement.

Usage

import { useImagePreload } from '@madeinhaus/hooks';
 
function MyComponent() {
  const [loaded, fnRef, imgRef] = useImagePreload();
 
  useEffect(() => {
    if (loaded) {
      console.log('Image loaded!', imgRef.current);
    }
  }, [loaded, imgRef]);
 
  return (
    <div>
      <img ref={fnRef} src="https://example.com/image.jpg" alt="Example" />
    </div>
  );
}

In this example, we import the useImagePreload hook from the @madeinhaus/hooks package, use it to monitor the loading state of an image and log a message when the image is loaded.