Last active
March 20, 2020 00:36
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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