Last active
November 10, 2025 19:59
-
-
Save devhammed/1042f7a5a10013204697757d2699781f to your computer and use it in GitHub Desktop.
React Hook For Managing Object URLs.
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 { useEffect, useState } from 'react'; | |
| export type BlobType = File | Blob | MediaSource | null; | |
| export function useObjectUrl(initialObject: BlobType | (() => BlobType) = null) { | |
| const [objectUrl, setObjectUrl] = useState<string | null>(null); | |
| const [object, setObject] = useState<BlobType>(initialObject); | |
| useEffect(() => { | |
| if (!object) { | |
| return; | |
| } | |
| const url = URL.createObjectURL(object); | |
| setObjectUrl(url); | |
| return () => { | |
| URL.revokeObjectURL(url); | |
| setObjectUrl(null); | |
| }; | |
| }, [object]); | |
| return { | |
| objectUrl, | |
| object, | |
| setObject, | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment