[](https://www.npmjs.com/package/react-native-ble-manager-hooks) [](http
npm install react-native-ble-manager-hooks


A React Native library providing custom hooks for react-native-ble-manager with advanced BLE command management features.
- 🔄 Command Queue Processing: Sequential command execution to prevent concurrency issues
- 🔌 Automatic Connection Management: Auto-reconnection with retry mechanism (up to 3 attempts)
- 📦 Singleton Pattern: Centralized BLE communication management
- 🎯 Response Matching: Automatic command-response matching with duplicate filtering
- âš¡ TypeScript Support: Full type definitions for better developer experience
- 🔗 Disconnection Detection: Built-in BLE disconnection event handling
- 📡 BLE State Management: Hooks for Bluetooth state, scanning, and peripheral management
- 🎣 React Hooks: Custom hooks for common BLE operations
This library uses react-native-ble-manager to handle Bluetooth Low Energy (BLE) operations. You must install and link react-native-ble-manager in your project first.
- React Native 0.60+
- iOS 8+ or Android (API 19+)
``bash`
npm install --save react-native-ble-manager-hooksor
yarn add react-native-ble-manager-hooks
Make sure you have installed and linked react-native-ble-manager in your project.
This library provides the following hooks:
- useBluetoothState() - Returns the current Bluetooth service stateuseBleManagerInit()
- - Manages BleManager initialization stateuseBlePeripheral()
- - Manages a specific BLE peripheral (device)useBleScan()
- - Manages the scanning process for peripheralsuseWrite()
- - Writes BLE commands with queue management
`typescript
import { useWrite } from "react-native-ble-manager-hooks";
const MyComponent = () => {
const { loading, onWriteCommand } = useWrite();
const sendCommand = async () => {
const [success, error] = await onWriteCommand({
command: 0x01,
packet: [0x00, 0x01, 0x02],
serviceData: {
peripheralId: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
serviceUUID: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
txCharacteristicUUID: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", // For notifications
rxCharacteristicUUID: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", // For writing
},
maxByteSize: 20, // Optional: default depends on device
});
if (error) {
console.error("Command failed:", error);
return;
}
if (success) {
console.log("Command succeeded:", success.value);
}
};
return (
{loading &&
);
};
`
`typescript
import { useWrite } from "react-native-ble-manager-hooks";
const MyComponent = () => {
const { loading, onWriteCommand } = useWrite({
onDisconnected: () => {
console.log("BLE device disconnected");
// Handle disconnection (e.g., show alert, navigate back)
},
onCatchError: (error) => {
console.error("Error occurred:", error);
// Custom error handling
},
successCondition: (response) => {
// Define custom success condition
return response.value[0] === 0x00;
},
errorCondition: (response) => {
// Define custom error condition
return response.value[0] !== 0x00;
},
});
const sendCommand = async () => {
const [success, error] = await onWriteCommand({
command: 0x01,
packet: [0x00, 0x01, 0x02],
serviceData: {
peripheralId: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
serviceUUID: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
txCharacteristicUUID: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
rxCharacteristicUUID: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
},
});
// Handle response
if (error) {
// error.value contains the error response data
handleError(error);
} else if (success) {
// success.value contains the success response data
handleSuccess(success);
}
};
// ... rest of component
};
`
`typescript
import { useBluetoothState } from "react-native-ble-manager-hooks";
import { BleState } from "react-native-ble-manager";
const MyComponent = () => {
const bluetoothState = useBluetoothState();
return (
Bluetooth State: {bluetoothState === BleState.On ? "On" : "Off"}
);
};
`
`typescript
import { useBleManagerInit } from "react-native-ble-manager-hooks";
import BleManager from "react-native-ble-manager";
const MyComponent = () => {
const { isInitialized, isInitializing, initError, initialize } =
useBleManagerInit({
autoInit: true, // Automatically initialize on mount
initOptions: { showAlert: false },
});
useEffect(() => {
if (isInitialized) {
// BleManager is ready, you can now use other hooks
console.log("BleManager initialized");
}
}, [isInitialized]);
// Or manually initialize
const handleInit = async () => {
await initialize();
};
return (
{isInitializing &&
{initError &&
{!isInitialized && }
);
};
`
`typescript
import { useBleScan } from "react-native-ble-manager-hooks";
const ScanComponent = () => {
const {
isScanning,
peripherals,
error,
startScan,
stopScan,
clearPeripherals,
} = useBleScan({
serviceUUIDs: ["XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"], // Optional
scanTimeLimit: 10000, // 10 seconds
allowDuplicates: false,
onPeripheralFound: (peripheral) => {
console.log("Found peripheral:", peripheral.name);
},
onScanStarted: () => {
console.log("Scan started");
},
onScanStopped: () => {
console.log("Scan stopped");
},
});
return (
title={isScanning ? "Stop Scan" : "Start Scan"}
onPress={isScanning ? stopScan : startScan}
/>
{peripherals.map((peripheral) => (
{peripheral.name || "Unknown"} - {peripheral.id}
))}
);
};
`
`typescript
import { useBlePeripheral } from "react-native-ble-manager-hooks";
const PeripheralComponent = () => {
const peripheralId = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX";
const {
connectionState,
isConnected,
isConnecting,
error,
connect,
disconnect,
retrieveServices,
startNotification,
stopNotification,
} = useBlePeripheral(peripheralId, {
onConnected: () => {
console.log("Connected!");
},
onDisconnected: () => {
console.log("Disconnected!");
},
onConnectionFailed: (error) => {
console.error("Connection failed:", error);
},
});
const handleConnect = async () => {
await connect();
const services = await retrieveServices();
if (services) {
// Start notification for a characteristic
await startNotification("SERVICE-UUID", "CHARACTERISTIC-UUID");
}
};
return (
{error &&
title={isConnected ? "Disconnect" : "Connect"}
onPress={isConnected ? disconnect : handleConnect}
disabled={isConnecting}
/>
);
};
`
The library automatically handles sequential command execution through the command queue. Commands are processed one at a time to prevent conflicts.
`typescript`
const sendMultipleCommands = async () => {
// These commands will be executed sequentially
const [result1] = await onWriteCommand({
command: 0x01,
packet: [0x00, 0x01],
serviceData: {
peripheralId: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
serviceUUID: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
txCharacteristicUUID: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
rxCharacteristicUUID: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
},
});
const [result2] = await onWriteCommand({
command: 0x02,
packet: [0x00, 0x02],
serviceData: {
peripheralId: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
serviceUUID: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
txCharacteristicUUID: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
rxCharacteristicUUID: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
},
});
};
Returns the current Bluetooth service state.
#### Returns
- BleState - Current Bluetooth state (Unknown, Resetting, Unsupported, Unauthorized, On, Off, TurningOn, TurningOff)
#### Example
`typescript`
const state = useBluetoothState();
// state will be one of: BleState.Unknown, BleState.On, BleState.Off, etc.
---
Manages BleManager initialization state.
#### Parameters
- options? (optional): Configuration objectautoInit?: boolean
- - Whether to auto-initialize on mount (default: false)initOptions?: StartOptions
- - Initialization options (see react-native-ble-manager docs)
#### Returns
- isInitialized: boolean - Whether BleManager is initializedisInitializing: boolean
- - Whether initialization is in progressinitError: any
- - Initialization error if anyinitialize: () => Promise
- - Function to manually initialize
---
Manages BLE peripheral scanning process.
#### Parameters
- options? (optional): Configuration objectserviceUUIDs?: string[]
- - Array of service UUIDs to scan forscanTimeLimit?: number
- - Scan time limit in millisecondsallowDuplicates?: boolean
- - Whether to allow duplicate peripherals (default: true)onPeripheralFound?: (peripheral: Peripheral) => void
- - Callback when peripheral is foundonScanStarted?: () => void
- - Callback when scan startsonScanStopped?: () => void
- - Callback when scan stops
#### Returns
- isScanning: boolean - Whether scanning is in progressperipherals: Peripheral[]
- - Array of discovered peripheralsperipheralsMap: Map
- - Map of discovered peripherals by IDerror: any
- - Scan error if anystartScan: () => Promise
- - Function to start scanningstopScan: () => Promise
- - Function to stop scanningclearPeripherals: () => void
- - Function to clear discovered peripherals list
---
Manages a specific BLE peripheral (device).
#### Parameters
- peripheralId?: string - ID of the peripheral to manageoptions?
- (optional): Configuration objectonDisconnected?: () => void
- - Callback when disconnectedonConnected?: () => void
- - Callback when connection succeedsonConnectionFailed?: (error: any) => void
- - Callback when connection fails
#### Returns
- peripheralId: string | undefined - The peripheral IDconnectionState: PeripheralConnectionState
- - Connection state (disconnected, connecting, connected, disconnecting)isConnected: boolean
- - Whether peripheral is connectedisConnecting: boolean
- - Whether connection is in progressisDisconnecting: boolean
- - Whether disconnection is in progresserror: any
- - Error if anyconnect: () => Promise
- - Function to connect to peripheraldisconnect: () => Promise
- - Function to disconnect from peripheralcheckConnection: () => Promise
- - Function to check connection statusretrieveServices: () => Promise
- - Function to retrieve servicesstartNotification: (serviceUUID: string, characteristicUUID: string) => Promise
- - Function to start notificationstopNotification: (serviceUUID: string, characteristicUUID: string) => Promise
- - Function to stop notification
---
A React hook that provides BLE command writing functionality with loading state and error handling.
#### Parameters
- options? (optional): Configuration objectonDisconnected?: () => void
- - Callback invoked when BLE device disconnectsonCatchError?: (error: any) => any
- - Error handler for command execution errorssuccessCondition?: (response: T) => boolean
- - Custom condition to determine successerrorCondition?: (response: T) => boolean
- - Custom condition to determine error
#### Returns
- loading: boolean - Loading state of the current commandonWriteCommand: (params: TWriteCommand) => Promise<[THandleUpdateValueForCharacteristicValue | undefined, THandleUpdateValueForCharacteristicValue | undefined]>
- - Function to send BLE commands
Command parameters interface:
`typescript`
interface TWriteCommand {
command: number; // Command identifier
packet: number[]; // Data packet to send
serviceData: TServiceInfo; // BLE service information
maxByteSize?: number; // Optional: Maximum byte size per write
}
Service information interface:
`typescript`
interface TServiceInfo {
peripheralId: string; // BLE device ID
serviceUUID: string; // Service UUID
txCharacteristicUUID: string; // Characteristic UUID for receiving notifications
rxCharacteristicUUID: string; // Characteristic UUID for writing commands
}
The onWriteCommand function returns a tuple:
`typescript`
[
success: THandleUpdateValueForCharacteristicValue | undefined,
error: THandleUpdateValueForCharacteristicValue | undefined
]
- First element: Success response (undefined if command failed)
- Second element: Error response (undefined if command succeeded)
- Both undefined: Command was cancelled or no response received
The response object structure:
`typescript``
interface THandleUpdateValueForCharacteristicValue {
value: number[]; // Response data as byte array
peripheral: string; // Peripheral ID
characteristic: string; // Characteristic UUID
service: string; // Service UUID
}
1. Command Queue: Commands are queued and processed sequentially to prevent race conditions
2. Connection Management: The library automatically checks connection status and reconnects if needed (up to 3 retries)
3. Response Matching: Responses are matched with commands using packet identifiers to filter duplicates
4. Error Handling: Comprehensive error handling with automatic retries for connection failures
5. Auto Cleanup: Resources are automatically cleaned up when the component unmounts
MIT
Contributions are welcome! Please feel free to submit a Pull Request.
For issues and feature requests, please use the GitHub Issues page.