useBarcode

A React hook that provides a high-level interface for detecting barcodes and QR codes in real-time using the browser's Barcode Detection API.

Warning

The Barcode Detection API is an experimental technology. Currently, it has limited browser support, primarily available in Chromium-based browsers.

Important

Camera access requires a Secure Context (HTTPS) and explicit user permission. The start() method will trigger the browser's permission prompt.

Tip

For optimal performance, provide a specific formats list to reduce the detector's processing overhead.

Installation

bash

Description

The useBarcode hook automates the lifecycle of barcode detection. It handles camera stream initialization (using the environment/rear camera by default), executes a continuous scanning loop via requestAnimationFrame, and manages the underlying BarcodeDetector instance. It can process input from video streams, static images, or canvas elements, returning the raw data and format of the first detected barcode.

Parameters

NameTypeDescription
elementRefReact.RefObject<HTMLVideoElement | HTMLImageElement | HTMLCanvasElement | null>A ref pointing to an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement or null. Default is undefined.
formatsstring[]An array of barcode formats to detect (e.g., ['qr_code', 'ean_13']). Defaults to a comprehensive list of common formats.
onDetect(barcode: DetectorBarcode) => voidOptional callback to be called when a barcode is detected.

Return values

NameTypeDescription
currentDetectorBarcode | nullAn object containing the format, rawValue, and boundingBox of the detected barcode, or null if none found.
start() => Promise<void>A function to start the scanning process.
stop() => voidA function to stop the scanning process.
supportedbooleanIndicates if the BarcodeDetector API is available in the user's browser environment.

Demo

This component is loading.

Source code

tsx