"use client";

import { useEffect, useMemo } from "react";

export function useObjectUrl(source: Blob | MediaSource | null | undefined) {
  const objectUrl = useMemo(() => {
    if (!source) {
      return null;
    }

    return URL.createObjectURL(source);
  }, [source]);

  useEffect(() => {
    return () => {
      if (objectUrl) {
        URL.revokeObjectURL(objectUrl);
      }
    };
  }, [objectUrl]);

  return objectUrl;
}
