Skip to content

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,
): FilePreviewState

Options

OptionTypeDefaultDescription
enabledbooleantrueSkip work when false
maxWidthnumberDownscale if wider
maxHeightnumberDownscale if taller

Returns

PropertyTypeDescription
previewUrlstring | nullObject URL, or null
isLoadingbooleantrue 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.

Released under the MIT License.