useBatteryStatus
A React hook to access system battery information via the Battery Status API
Installation
Props
The hook returns an object with the following properties:
Property | Type | Description |
---|---|---|
supported | boolean | Whether the Battery Status API is supported |
level | number | Current battery level (0 to 1) |
charging | boolean | Whether the battery is currently charging |
chargingTime | number | Time in seconds until the battery is fully charged |
dischargingTime | number | Time in seconds until the battery is fully discharged |
Key Features & Details
- Real-time battery information with automatic updates via the Battery Status API events.
- Graceful fallback when the API is not supported.
- Simple and declarative interface for easy integration.
Examples
Basic Usage
const { supported, level, charging } = useBatteryStatus();
if (supported) {
console.log(`Battery level: ${level * 100}%`);
} else {
console.warn('Battery Status API not supported');
}
Full Example
import React from 'react';
import { useBatteryStatus } from '@/registry/hooks/use-battery-status';
export default function BatteryComponent() {
const { supported, level, charging, chargingTime, dischargingTime } =
useBatteryStatus();
if (!supported) {
return <p>Battery API not supported</p>;
}
return (
<div>
<p>Level: {Math.round(level * 100)}%</p>
<p>Status: {charging ? 'Charging' : 'Discharging'}</p>
<p>Charging Time: {chargingTime}s</p>
<p>Discharging Time: {dischargingTime}s</p>
</div>
);
}