typescriptadvanced
useMediaRecorder Hook
Wraps the MediaRecorder API for audio/video recording with start, stop, and blob output.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { useState, useRef, useCallback } from 'react';
interface UseMediaRecorderOptions {
mimeType?: string;
audio?: boolean;
video?: boolean;
}
export function useMediaRecorder(options: UseMediaRecorderOptions = { audio: true }) {
const [recording, setRecording] = useState(false);
const [blob, setBlob] = useState<Blob | null>(null);
const [error, setError] = useState<string | null>(null);
const recorderRef = useRef<MediaRecorder | null>(null);
const chunksRef = useRef<Blob[]>([]);
const start = useCallback(async () => {
try {
const stream = await navigator.mediaDevices.getUserMedia({
audio: options.audio ?? true,
video: options.video ?? false,
});
const recorder = new MediaRecorder(stream, {
mimeType: options.mimeType || 'audio/webm',
});
chunksRef.current = [];
recorder.ondataavailable = (e) => chunksRef.current.push(e.data);
recorder.onstop = () => {
const recorded = new Blob(chunksRef.current, { type: recorder.mimeType });
setBlob(recorded);
stream.getTracks().forEach(t => t.stop());
};
recorder.start();
recorderRef.current = recorder;
setRecording(true);
setError(null);
} catch (err) {
setError(err instanceof Error ? err.message : 'Recording failed');
}
}, [options]);
const stop = useCallback(() => {
recorderRef.current?.stop();
setRecording(false);
}, []);
return { recording, blob, error, start, stop };
}Use Cases
- Voice memos
- Video testimonials
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
useFetch — Generic Data Fetching Hook
Custom React hook for data fetching with loading, error, and refetch states using the Fetch API.
Best for: API data fetching
#hooks#fetch
typescriptbeginner
useDebounce — Debounced Value Hook
Debounce any rapidly-changing value with a configurable delay. Useful for search inputs and resize handlers.
Best for: Search-as-you-type
#hooks#debounce
typescriptintermediate
useLocalStorage — Persistent State Hook
Sync React state with localStorage including SSR safety, JSON serialization, and cross-tab updates.
Best for: User preferences
#hooks#localstorage
typescriptbeginner
useClickOutside — Outside Click Detection
Detect clicks outside a referenced element to close dropdowns, modals, and popover menus.
Best for: Dropdown menus
#hooks#click-outside