Importantnavigator.mediaDevices.getUserMedia only works in secure contexts (HTTPS). It will also work on localhost for development purposes, but it will fail silently or throw errors on standard HTTP deployments.
WarningAlways call the stop() function when the user leaves the camera view. Leaving the camera active drains battery and keeps the hardware "in-use" light on, which is a poor user experience.
CautionSome older mobile browsers or embedded webviews (like those inside social media apps) may not fully support the mediaDevices API. Always check the return value of requestPermission.
NoteThis hook automatically calculates the height based on the video's natural aspect ratio. Ensure your CSS for the video and img elements accounts for dynamic heights to prevent layout shifts.
TipUse the blob provided in the onCapture callback if you intend to upload the image to a server (e.g., via FormData). It is significantly more efficient than sending a large Base64 string.
This hook provides an end-to-end interface for handling the MediaDevices API. It handles permission requests, manages the video stream lifecycle (start/stop), calculates aspect ratios automatically based on a desired width, and provides helper refs to render the live feed and the final captured image.
| Name | Type | Description |
|---|---|---|
| options.format | CameraCaptureOutput | Optional output format for the captured image. Default: type: image/png, quality: 0.8 |
| options.onCapture | (dataUrl: string, blob: Blob) => void | Optional callback triggered after a successful capture. Provides both the Base64 string and the raw File Blob. |
| options.width | number | The desired output width of the image. Height is scaled automatically. Default: 320. |
| Name | Type | Description |
|---|---|---|
| canvasRef | React.RefObject<HTMLCanvasElement | null> | Ref to the hidden <canvas /> used for processing the image data. |
| capture | () => string | null | Captures the current frame, renders it to the imageRef, and returns the Data URL. |
| imageRef | React.RefObject<HTMLImageElement | null> | Ref to attach to an <img /> tag to display the last captured photo. |
| requestPermission | () => Promise<boolean> | Async function that prompts the user for camera access and starts the stream. |
| stop | () => void | Releases the camera hardware and stops all active media tracks. |
| usePermission | () => boolean | Returns whether the user has successfully granted camera access. |
| useStreaming | () => boolean | Returns the current active state of the video stream. |
| videoRef | React.RefObject<HTMLVideoElement | null> | Ref to attach to the <video /> tag for the live stream. |