useCamera
getUserMedia camera stream.
Import
TypeScript
import { useCamera } from '@/hooks';API
Signature
useCamera(options?) → { stream, start, stop, error }
When to use
Use useCamera 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 · useCameraEditor
function Webcam() { const videoRef = useRef<HTMLVideoElement>(null); const { stream, start, stop, error } = useCamera({ enabled: false }); useEffect(() => { if (videoRef.current) videoRef.current.srcObject = stream; }, [stream]); return ( <div> <video ref={videoRef} autoPlay muted playsInline /> <button onClick={() => void start()}>Start</button> <button onClick={stop}>Stop</button> {error && <p>{error.message}</p>} </div> ); }
Preview
Implementation source
Full library source for useCamera — copy into your project when you are not installing a package yet.
hooks/media/useCamera.ts
import { useCallback, useEffect, useRef, useState } from 'react';
import { hasNavigator, isBrowser } from '../utility/isBrowser';
export interface UseCameraOptions {
enabled?: boolean;
constraints?: MediaStreamConstraints['video'];
}
/** Request a camera stream and release tracks on cleanup. */
export function useCamera(options: UseCameraOptions = {}) {
const { enabled = true, constraints = true } = options;
const [stream, setStream] = useState<MediaStream | null>(null);
const [error, setError] = useState<Error | null>(null);
const [loading, setLoading] = useState(false);
const streamRef = useRef<MediaStream | null>(null);
const stop = useCallback(() => {
streamRef.current?.getTracks().forEach((t) => t.stop());
streamRef.current = null;
setStream(null);
}, []);
const start = useCallback(async () => {
if (!isBrowser() || !hasNavigator() || !navigator.mediaDevices?.getUserMedia) {
setError(new Error('Camera API is not supported'));
return null;
}
setLoading(true);
setError(null);
try {
stop();
const media = await navigator.mediaDevices.getUserMedia({
video: constraints,
audio: false,
});
streamRef.current = media;
setStream(media);
return media;
} catch (e) {
const err = e instanceof Error ? e : new Error(String(e));
setError(err);
return null;
} finally {
setLoading(false);
}
}, [constraints, stop]);
useEffect(() => {
if (enabled) void start();
else stop();
return stop;
}, [enabled]);
const supported =
isBrowser() && hasNavigator() && !!navigator.mediaDevices?.getUserMedia;
return { stream, error, loading, start, stop, supported };
}
Copy-paste example
useCamera.example.tsx
'use client';
import { useEffect, useRef } from 'react';
import { useCamera } from '@/hooks';
export function Webcam() {
const videoRef = useRef<HTMLVideoElement>(null);
const { stream, start, stop, error } = useCamera({ enabled: false });
useEffect(() => {
if (videoRef.current) videoRef.current.srcObject = stream;
}, [stream]);
return (
<div>
<video ref={videoRef} autoPlay muted playsInline />
<button onClick={() => void start()}>Start</button>
<button onClick={stop}>Stop</button>
{error && <p>{error.message}</p>}
</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/useCamera.tsfor implementation details