Skip to content

Instantly share code, notes, and snippets.

@devhammed
Last active November 10, 2025 19:59
Show Gist options
  • Select an option

  • Save devhammed/1042f7a5a10013204697757d2699781f to your computer and use it in GitHub Desktop.

Select an option

Save devhammed/1042f7a5a10013204697757d2699781f to your computer and use it in GitHub Desktop.
React Hook For Managing Object URLs.
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