Skip to content

Instantly share code, notes, and snippets.

@SleeplessByte
Last active March 20, 2020 00:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SleeplessByte/e942759e429eeb3daed3660bcf84da03 to your computer and use it in GitHub Desktop.
Save SleeplessByte/e942759e429eeb3daed3660bcf84da03 to your computer and use it in GitHub Desktop.
Simple hook that creates a file preview and revokes it when it's no longer needed.
import { useState, useEffect } from 'react'
type FilePreview = string | null
export function useFilePreview(
nextFile: File | undefined,
defaultPreview: FilePreview = null
): FilePreview {
const [preview, setPreview] = useState<FilePreview>(null)
useEffect(() => {
// Make the preview if there is a file
const objectUrl = nextFile && URL.createObjectURL(nextFile)
setPreview(objectUrl || null)
// Release resources if a preview was created
return () => {
objectUrl && URL.revokeObjectURL(objectUrl)
}
}, [nextFile])
return preview || defaultPreview
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment