useFilePreview
Creates an object-URL preview for a File (typically an image) and revokes it on unmount or when the file changes.
ts
function useFilePreview(
file: File | null | undefined,
options?: FilePreviewOptions,
): FilePreviewStateOptions
| Option | Type | Default | Description |
|---|---|---|---|
enabled | boolean | true | Skip work when false |
maxWidth | number | — | Downscale if wider |
maxHeight | number | — | Downscale if taller |
Returns
| Property | Type | Description |
|---|---|---|
previewUrl | string | null | Object URL, or null |
isLoading | boolean | true while a resize is in progress |
Without maxWidth / maxHeight, the hook uses URL.createObjectURL(file) directly (isLoading stays false). With either dimension set, it draws to a canvas, emits a resized blob URL, and sets isLoading until that blob is ready.
Always pass enabled: file.type.startsWith('image/') (or equivalent). Non-image files still get an object URL if you leave enabled true — the browser will not render them in <img>.
Example
tsx
function Thumb({ file }: { file: File }) {
const isImage = file.type.startsWith('image/');
const { previewUrl, isLoading } = useFilePreview(file, {
enabled: isImage,
maxWidth: 96,
maxHeight: 96,
});
if (!isImage) return <span>{file.name.split('.').pop()}</span>;
if (isLoading || !previewUrl) return <span>…</span>;
return <img src={previewUrl} alt={file.name} />;
}Do not revokeObjectURL yourself. The hook owns the URL lifetime. Do not store previewUrl in global state after unmount.
FileList already calls this hook per row. Use useFilePreview directly when you render the list yourself.