useCameraCapture

A hook that manages camera access and simplifies capturing still images from a live video stream via a canvas element.

Important

navigator.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.

Warning

Always 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.

Caution

Some 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.

Note

This 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.

Tip

Use 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.

Installation

bash

Description

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.

Parameters

NameTypeDescription
options.formatCameraCaptureOutputOptional output format for the captured image. Default: type: image/png, quality: 0.8
options.onCapture(dataUrl: string, blob: Blob) => voidOptional callback triggered after a successful capture. Provides both the Base64 string and the raw File Blob.
options.widthnumberThe desired output width of the image. Height is scaled automatically. Default: 320.

Return values

NameTypeDescription
canvasRefReact.RefObject<HTMLCanvasElement | null>Ref to the hidden <canvas /> used for processing the image data.
capture() => string | nullCaptures the current frame, renders it to the imageRef, and returns the Data URL.
imageRefReact.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() => voidReleases the camera hardware and stops all active media tracks.
usePermission() => booleanReturns whether the user has successfully granted camera access.
useStreaming() => booleanReturns the current active state of the video stream.
videoRefReact.RefObject<HTMLVideoElement | null>Ref to attach to the <video /> tag for the live stream.

Demo

Camera Capture

Permission: DeniedStreaming: Inactive
Live Stream
Last CaptureLast capture

Source code

tsx