Skip to content

useBluetooth ​

Hook to connect and interact with bluetooth devices.

See: Web Bluetooth API.

Demo ​

INFO

The component uses useBluetooth hook to detect if Bluetooth API is supported and show all available bluetooth devices and show renders its name after connection.

Loading demo…
Show source code
tsx
import { useCallback, useState } from "react";
import { useBluetooth } from "../../../.."

export const UseBluetooth = () => {
	const [value, requestDevice] = useBluetooth();

	const [error, setError] = useState("");

	const getDevice = useCallback(() => {
		requestDevice().catch(err => {
			if (err instanceof Error) {
				setError(err.message);
			} else {
				setError(err as string);
			}
		})
	}, [requestDevice]);

	return <>
		<p>
			Bluetooth supported: {value.isSupported ? "Yes" : "No"}
		</p>
		{
			value.isConnected &&
			<p>
					Device Name: {value.device?.name}
			</p>
		}
		<button type="button" onClick={getDevice} disabled={!value.isSupported}>Get Bluetooth device</button>
		{
			error &&
			<p style={{color: 'red'}}>
					{error}
			</p>
		}
	</>
}

Types ​

Bluetooth ​

The navigator.bluetooth interface, extended with the requestDevice method. Used internally by useBluetooth.

PropertyTypeRequiredDescription
requestDevice(opts?: BluetoothDevicesOptions) => Promise<BluetoothDevice \| TypeError \| DOMException>✓Prompts the user to select a Bluetooth device matching the provided options.

BluetoothDevicesOptions ​

Options passed to Bluetooth.requestDevice().

PropertyTypeRequiredDescription
filtersBluetoothScanFilters[]Array of scan filters. The browser only shows devices that match at least one filter. Each filter can specify services, name, and/or namePrefix.
optionalServicesBluetoothServiceUUID[]Array of additional GATT service UUIDs that the requesting script wants to access, beyond those specified in filters.
acceptAllDevicesbooleanWhen true, the browser shows all discoverable Bluetooth devices regardless of filters. Use with caution — requires user consent for every device.

BluetoothServiceUUID ​

A UUID identifying a Bluetooth GATT service. Can be a 16-bit short UUID (number) or a full 128-bit UUID string.

number | string

BluetoothCharacteristicUUID ​

A UUID identifying a Bluetooth GATT characteristic.

number | string

BluetoothDescriptorUUID ​

A UUID identifying a Bluetooth GATT descriptor.

number | string

BluetoothDevice ​

Represents a Bluetooth device inside the current script execution environment.

PropertyTypeRequiredDescription
idstring✓A unique string identifying the device across sessions in the same origin.
namestring✓Human-readable name provided by the device (e.g. "My Headphones").
gattBluetoothRemoteGATTServer✓Reference to the device's primary GATT server. Use this to discover services and characteristics.

BluetoothRemoteGATTServer ​

Represents a GATT Server hosted on a remote Bluetooth device.

PropertyTypeRequiredDescription
connectedboolean✓true while this script execution environment is connected to the device. Note: may be false even when the physical connection is still alive.
deviceBluetoothDevice✓The BluetoothDevice this server belongs to.
connect() => Promise<BluetoothRemoteGATTServer>✓Establishes a GATT connection to the device.
disconnect() => void✓Disconnects from the remote GATT server.
getPrimaryService(uuid: BluetoothServiceUUID) => Promise<BluetoothRemoteGATTService>✓Returns a Promise to the primary GATT service with the given UUID.
getPrimaryServices(uuid: BluetoothServiceUUID) => Promise<BluetoothRemoteGATTService[]>✓Returns a Promise to all primary GATT services with the given UUID.

BluetoothRemoteGATTService ​

Represents a GATT service on a remote Bluetooth device.

PropertyTypeRequiredDescription
deviceBluetoothDevice✓The BluetoothDevice this service belongs to.
isPrimaryboolean✓true if this is a primary service; false if it is secondary.
uuidBluetoothServiceUUID✓UUID string identifying this service (e.g. "0000180d-0000-1000-8000-00805f9b34fb").
getCharacteristic(uuid: BluetoothCharacteristicUUID) => Promise<BluetoothRemoteGATTCharacteristic>✓Returns a Promise to the characteristic with the given UUID within this service.
getCharacteristics(uuid: BluetoothCharacteristicUUID) => Promise<BluetoothRemoteGATTCharacteristic[]>✓Returns a Promise to all characteristics with the given UUID within this service.

BluetoothRemoteGATTCharacteristic ​

Represents a GATT Characteristic, the basic data element of a Bluetooth service.

PropertyTypeRequiredDescription
serviceBluetoothRemoteGATTService✓The BluetoothRemoteGATTService this characteristic belongs to.
uuidBluetoothCharacteristicUUID✓UUID string identifying this characteristic (e.g. "00002a37-0000-1000-8000-00805f9b34fb").
propertiesBluetoothCharacteristicProperties✓Object describing which operations (read, write, notify, etc.) are permitted.
valueArrayBuffer✓The most recently cached value, updated on read or via notification/indication.
oncharacteristicvaluechanged(evt: EventTarget) => void✓Event handler called when the characteristic value changes (notification/indication).
getDescriptor(uuid: BluetoothDescriptorUUID) => Promise<BluetoothRemoteGATTDescriptor>✓Returns the first GATT descriptor with the given UUID.
getDescriptors(uuid: BluetoothDescriptorUUID) => Promise<BluetoothRemoteGATTDescriptor[]>✓Returns all GATT descriptors with the given UUID.
readValue() => Promise<DataView>✓Reads and returns the current value of the characteristic.
writeValue(value: ArrayBuffer) => Promise<void>✓Writes a value to the characteristic (response optional).
writeValueWithResponse(value: ArrayBuffer) => Promise<void>✓Writes a value and waits for confirmation from the device.
writeValueWithoutResponse(value: ArrayBuffer) => Promise<void>✓Writes a value without requesting confirmation from the device.
startNotifications() => Promise<BluetoothRemoteGATTCharacteristic>✓Subscribes to value change notifications for this characteristic.
stopNotifications() => Promise<void>✓Unsubscribes from value change notifications for this characteristic.

BluetoothCharacteristicProperties ​

Permission flags describing which operations are allowed on a GATT characteristic.

PropertyTypeRequiredDescription
authenticatedSignedWritesboolean✓true if authenticated signed writes are permitted.
broadcastboolean✓true if broadcasting the value via the Server Characteristic Configuration Descriptor is permitted.
indicateboolean✓true if indications (acknowledged notifications) are permitted.
notifyboolean✓true if notifications (unacknowledged) are permitted.
readboolean✓true if reading the characteristic value is permitted.
reliableWriteboolean✓true if reliable writes are permitted.
writableAuxiliariesboolean✓true if writing to the characteristic descriptor is permitted.
writeboolean✓true if writing with response is permitted.
writeWithoutResponseboolean✓true if writing without response is permitted.

BluetoothRemoteGATTDescriptor ​

Represents a GATT Descriptor, providing additional metadata about a characteristic's value.

PropertyTypeRequiredDescription
characteristicBluetoothRemoteGATTCharacteristic✓The characteristic this descriptor is attached to.
uuidBluetoothDescriptorUUID✓UUID string of this descriptor (e.g. "00002902-0000-1000-8000-00805f9b34fb" for CCCD).
valueArrayBuffer✓The most recently cached descriptor value. Updated on read.
readValue() => Promise<ArrayBuffer>✓Reads and returns the current descriptor value.
writeValue(value: ArrayBuffer) => Promise<void>✓Writes a value to the descriptor.

BluetoothScanFilters ​

Scan filter for Bluetooth.requestDevice(). A device matches if it satisfies at least one of the provided filters.

Each variant requires at least one of: name, namePrefix, or services.

ts
export type BluetoothScanFilters =
	| { name: string; namePrefix: string; services: BluetoothServiceUUID[] }
	| { name: string; namePrefix?: never; services?: never }
	| { name: string; namePrefix: string; services?: never }
	| { name: string; namePrefix?: never; services: BluetoothServiceUUID[] }
	| { name?: never; namePrefix: string; services: BluetoothServiceUUID[] }
	| { name?: never; namePrefix?: never; services: BluetoothServiceUUID[] }
	| { name?: never; namePrefix: string; services?: never };

UseBluetoothState ​

Reactive state snapshot returned as the first element of useBluetooth's tuple.

PropertyTypeRequiredDescription
isSupportedboolean✓true when the Web Bluetooth API (navigator.bluetooth) is available in the current browser. When false, requestDevice will not open a picker.
isConnectedboolean✓true when a GATT connection to a device is currently active. Becomes false after server.disconnect() is called or the device goes out of range.
deviceBluetoothDevice \| null✓The selected BluetoothDevice returned by the browser's device picker. null before the user selects a device or after disconnection.
serverBluetoothRemoteGATTServer \| null✓The BluetoothRemoteGATTServer for the selected device. Use this to discover services and characteristics. null until a GATT connection is established.

UseBluetoothResult ​

Result tuple returned by useBluetooth.

IndexTypeDescription
[0]UseBluetoothStateReactive Bluetooth state (supported, connected, device, server). See {@link UseBluetoothState}.
[1](opts?: BluetoothDevicesOptions) => Promise<void>requestDevice — opens the browser's Bluetooth device picker. Connect to the GATT server of the chosen device.
IndexTypeDescription
[0]UseBluetoothState
[1](opts?: BluetoothDevicesOptions) => Promise<void>

Released under the MIT License.