Skip to content

useImageLoader

Use this hook to load an image in the background using its URL, and returns its loading state.

Parameters

  1. the image URL.
  2. the load event handler function.

Return Values

NameTypeDescription
imageHTMLImageElementthe loaded image.
isLoadingBooleanthe image loading state.
isErrorBooleanindicates whether there is an error or not.

Example Usage

tsx
import { useImageLoader } from 'react-pre-hooks';

const url = 'https://picsum.photos/1280/960';

export default function Example() {
  const { isLoading, image } = useImageLoader(url, () => console.log('Loaded.'));

  return (
    <main>
      {isLoading ? (
        <div>Loading...</div>
      ) : (
        <div>
          <img src={url} alt="image" />
          <p>
            Width: {image.width}, Height: {image.height}
          </p>
        </div>
      )}
    </main>
  );
}
import { useImageLoader } from 'react-pre-hooks';

const url = 'https://picsum.photos/1280/960';

export default function Example() {
  const { isLoading, image } = useImageLoader(url, () => console.log('Loaded.'));

  return (
    <main>
      {isLoading ? (
        <div>Loading...</div>
      ) : (
        <div>
          <img src={url} alt="image" />
          <p>
            Width: {image.width}, Height: {image.height}
          </p>
        </div>
      )}
    </main>
  );
}

Released under the MIT License.