Files
skills/docs/foundation/data/react-packer/src/hooks/use-packed-image/use-packed-image.md
2026-05-29 08:20:56 +01:00

2.6 KiB

usePackedImage — image-tuned packed-resource hook

(no submodules)

Purpose

usePackedImage is a thin wrapper around usePackedResource that pre-fills sensible defaults for image assets: caching is enabled (images tend to be re-used across renders) and the manager's MIME allow-list is narrowed to image/-prefixed types so a misconfigured archive serving HTML or JavaScript under a virtual image URL fails fast at the loader boundary rather than the <img> tag.

The hook returns the same UsePackedResourceReturn shape as the generic hook, so it is drop-in for any component that already consumes usePackedResource.

Features

  • cache: true default — caller can opt out with { cache: false }.
  • allowedMimePrefixes: ["image/"] default — caller can broaden or narrow.
  • Forwards verifyKey, verifyChecksum, and signal untouched.
  • Identical return shape to usePackedResource for trivial swapping.

Usage: Basic

import { usePackedImage } from "@suaveplan/react-packer";

function Avatar({ src }: { src: string | null }) {
    const { url, loading } = usePackedImage(src);
    if (loading) return <div className="avatar avatar--loading" />;
    return url !== null ? <img alt="" className="avatar" src={url} /> : null;
}

Usage: Advanced

import { usePackedImage } from "@suaveplan/react-packer";

function SignedAvatar({
    src,
    key,
}: {
    src: string;
    key: Uint8Array;
}) {
    const { url, error } = usePackedImage(src, {
        verifyChecksum: true,
        verifyKey: key,
        allowedMimePrefixes: ["image/avif", "image/webp"],
    });
    if (error !== null) return <span>{error.code}</span>;
    return url !== null ? <img alt="" src={url} /> : null;
}

API Reference

  • usePackedImage(packedUrl, options?): UsePackedResourceReturn
  • Behaviour is identical to usePackedResource except defaults differ:
    • cache defaults to true.
    • allowedMimePrefixes defaults to ["image/"].
  • All other options pass through unchanged.

Implementation Notes

  • Defaults apply only when the caller omits the key — explicit false or an empty array opt out of caching / MIME enforcement respectively.
  • The MIME allow-list is honoured by the manager's loader, not by the hook itself; non-image archives surface as ReactPackerError(LOAD_FAILED) with the underlying PackerBrowserError(UNSUPPORTED_RESOURCE_TYPE) on .cause.
  • The constant IMAGE_MIME_PREFIXES is module-local and frozen via ReadonlyArray typing so consumers cannot mutate the default.