useImagePreview Hook

A hook for previewing an image file

Code Snippet

useImagePreview.ts
import { useState, useEffect } from 'react';

export default function useImagePreview(imageFile: File | null) {
  const [previewSrc, setPreviewSrc] = useState('');

  useEffect(() => {
    if (!imageFile) return;

    const reader = new FileReader();

    reader.onloadend = () => {
      setPreviewSrc(reader.result as string);
    };

    reader.readAsDataURL(imageFile);

    return () => {
      reader.abort();
    };
  }, [imageFile]);

  return previewSrc;
}

Usage

Assuming that you already have a markup (a file input and an image element), use the hook as follows:

  1. Create a state for your image file like this:
const [imageFile, setImageFile] = useState<File | null>(null);
  1. Pass imageFile as the argument for the hook and use its return value previewSrc:
const previewSrc = useImagePreview(imageFile);
  1. Assign the value of previewSrc to your image's src:
<img
  src={previewSrc}
  alt='a sample preview'
  width='100%'
  height='100%'
  style={{ objectFit: 'cover' }} // the style depends on your requirements
/>