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.
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";23const 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};1516<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
refand spreadhandlerson the element that wraps the image.loadanderrordo not bubble, so the handlers use React's capture phase and work with any component that renders an<img>inside, such asnext/image. resetKeynames the image. A new key starts again atloading; an image that changed without a new key keeps its earlier status, so key it by the image'ssrc.- An image that finished or broke before hydration fires no event, so a new key also reads
completeandnaturalWidthfrom the DOM.
Examples
Open all 1 →1const LOADED_IMAGE =2 "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='160' height='100'><rect width='160' height='100' fill='%23c9b6e4'/></svg>";34const BROKEN_IMAGE = "/image-that-does-not-exist.jpg";56const StatusImage = ({ src, alt }: { src: string; alt: string }) => {7 const { ref, status, handlers } = useImageStatus(src);89 return (10 <div ref={ref} {...handlers}>11 <img src={src} alt={alt} width={160} height={100} />12 <p>Status: {status}</p>13 </div>14 );15};1617const BasicUseImageStatus = () => (18 <>19 <StatusImage src={LOADED_IMAGE} alt="A lilac swatch" />20 <StatusImage src={BROKEN_IMAGE} alt="A missing picture" />21 </>22);2324render(<BasicUseImageStatus />);
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>| Parameter | Type | Default | Description |
|---|---|---|---|
resetKey | string | — | 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.
1const { ref, status, handlers } = useImageStatus(src);2<div ref={ref} {...handlers}>3 {status === "error" ? <Fallback /> : <img src={src} alt="" />}4</div>