MediaAdvancedSSR-safehooks/media/useMediaRecorder.ts

useMediaRecorder

Record a MediaStream.

Import

TypeScript
import { useMediaRecorder } from '@/hooks';

API

Signature

useMediaRecorder({ stream?, mimeType? })

When to use

Use useMediaRecorder instead of re-implementing the same pattern in multiple components.

SSR / Next.js

Client-only browser APIs.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useMediaRecorder
Editor
function Recorder() {
  const cam = useCamera({ enabled: true });
  const rec = useMediaRecorder({ stream: cam.stream });
  return (
    <div>
      <button onClick={rec.start} disabled={rec.recording}>Rec</button>
      <button onClick={rec.stop} disabled={!rec.recording}>Stop</button>
      {rec.blob && <a href={URL.createObjectURL(rec.blob)} download>Download</a>}
    </div>
  );
}
Preview

Implementation source

Full library source for useMediaRecorder — copy into your project when you are not installing a package yet.

hooks/media/useMediaRecorder.ts
import { useCallback, useEffect, useRef, useState } from 'react';
import { isBrowser } from '../utility/isBrowser';

export interface UseMediaRecorderOptions {
  stream?: MediaStream | null;
  mimeType?: string;
}

/**
 * MediaRecorder wrapper. Stops recorder and does not own the stream
 * lifecycle unless you pass your own stream management.
 */
export function useMediaRecorder(options: UseMediaRecorderOptions = {}) {
  const { stream, mimeType } = options;
  const recorderRef = useRef<MediaRecorder | null>(null);
  const chunksRef = useRef<Blob[]>([]);
  const [recording, setRecording] = useState(false);
  const [paused, setPaused] = useState(false);
  const [error, setError] = useState<Error | null>(null);
  const [blob, setBlob] = useState<Blob | null>(null);

  const supported =
    isBrowser() && typeof MediaRecorder !== 'undefined';

  const stop = useCallback(() => {
    const rec = recorderRef.current;
    if (rec && rec.state !== 'inactive') {
      rec.stop();
    }
    setRecording(false);
    setPaused(false);
  }, []);

  const start = useCallback(() => {
    if (!supported || !stream) {
      setError(new Error('MediaRecorder is not available or stream is missing'));
      return;
    }
    try {
      chunksRef.current = [];
      setBlob(null);
      const rec = new MediaRecorder(
        stream,
        mimeType ? { mimeType } : undefined,
      );
      recorderRef.current = rec;
      rec.ondataavailable = (e) => {
        if (e.data.size > 0) chunksRef.current.push(e.data);
      };
      rec.onstop = () => {
        const b = new Blob(chunksRef.current, {
          type: rec.mimeType || mimeType || 'video/webm',
        });
        setBlob(b);
      };
      rec.onerror = () => setError(new Error('MediaRecorder error'));
      rec.start();
      setRecording(true);
      setPaused(false);
      setError(null);
    } catch (e) {
      setError(e instanceof Error ? e : new Error(String(e)));
    }
  }, [supported, stream, mimeType]);

  const pause = useCallback(() => {
    if (recorderRef.current?.state === 'recording') {
      recorderRef.current.pause();
      setPaused(true);
    }
  }, []);

  const resume = useCallback(() => {
    if (recorderRef.current?.state === 'paused') {
      recorderRef.current.resume();
      setPaused(false);
    }
  }, []);

  useEffect(() => () => stop(), [stop]);

  return {
    supported,
    recording,
    paused,
    error,
    blob,
    start,
    stop,
    pause,
    resume,
  };
}

Copy-paste example

useMediaRecorder.example.tsx
'use client';

import { useCamera, useMediaRecorder } from '@/hooks';

export function Recorder() {
  const cam = useCamera({ enabled: true });
  const rec = useMediaRecorder({ stream: cam.stream });
  return (
    <div>
      <button onClick={rec.start} disabled={rec.recording}>Rec</button>
      <button onClick={rec.stop} disabled={!rec.recording}>Stop</button>
      {rec.blob && <a href={URL.createObjectURL(rec.blob)} download>Download</a>}
    </div>
  );
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Always stop tracks on unmount (hooks clean up streams they own).
  • Source of truth: open hooks/media/useMediaRecorder.ts for implementation details