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
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 →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>