2.6 KiB
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: truedefault — caller can opt out with{ cache: false }.allowedMimePrefixes: ["image/"]default — caller can broaden or narrow.- Forwards
verifyKey,verifyChecksum, andsignaluntouched. - Identical return shape to
usePackedResourcefor 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
usePackedResourceexcept defaults differ:cachedefaults totrue.allowedMimePrefixesdefaults to["image/"].
- All other options pass through unchanged.
Implementation Notes
- Defaults apply only when the caller omits the key — explicit
falseor 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 underlyingPackerBrowserError(UNSUPPORTED_RESOURCE_TYPE)on.cause. - The constant
IMAGE_MIME_PREFIXESis module-local and frozen viaReadonlyArraytyping so consumers cannot mutate the default.