Tracks whether the image inside a wrapper is loading, loaded or failed, whatever component drew it, so a card or a gallery can swap a broken image for a fallback.

pnpm add @behivetech/hooks.use-image-status

You are viewing Use Image Status v0.1.0, snapshotted 2026-11-09. The latest is v0.1.1. Go to the latest →

Tracks whether the image inside a wrapper is loading, loaded or failed, whatever component drew it, so a card or a gallery can swap a broken image for a fallback.

Usage

1import { useImageStatus } from "@behivetech/hooks.use-image-status";
2
3const Example = () => {
4 const { ref, status, handlers } = useImageStatus("/blue-hour.jpg");
5 return (
6 <div ref={ref} {...handlers}>
7 {status === "error" ? (
8 <span>Image unavailable</span>
9 ) : (
10 <img src="/blue-hour.jpg" alt="Blue hour on the porch" />
11 )}
12 </div>
13 );
14};
15
16<Example />;

The ```jsx block above runs live on the docs site. The signature, parameters and return value shown there come from the hook's TypeScript and JSDoc; keep the @param, @returns and @example tags current.

Behaviour

  • Attach ref and spread handlers on the element that wraps the image. load and error do not bubble, so the handlers use React's capture phase and work with any component that renders an <img> inside, such as next/image.
  • resetKey names the image. A new key starts again at loading; an image that changed without a new key keeps its earlier status, so key it by the image's src.
  • An image that finished or broke before hydration fires no event, so a new key also reads complete and naturalWidth from the DOM.

Hooks

useImageStatus hook

Tracks whether the `<img>` inside a wrapper has loaded or failed, whatever component drew it (a plain `<img>` or an app's `next/image`). `resetKey` names the image: a new key starts again at `loading`. An image that settled before hydration fires no event, so a new key also reads `complete`.

useImageStatus(resetKey: string): ImageStatusResult<T>
ParameterTypeDefaultDescription
resetKeystring—Names the image; change it when the image changes.

Returns ImageStatusResult<T> — A ref and the capture handlers for the wrapper, the status, and the alt text of a failed image.

Example
1const { ref, status, handlers } = useImageStatus(src);
2<div ref={ref} {...handlers}>
3 {status === "error" ? <Fallback /> : <img src={src} alt="" />}
4</div>