useBattery
Hook for accessing and monitoring device battery status.
See: Battery Status API.
Demo
INFO
The component displays device battery information.
Loading demo…
Show source code
tsx
import { useBattery } from "../../../.."
export const UseBattery = () => {
const status = useBattery();
return (<div style={{ textAlign: "center" }}>
{
Object.keys(status).map(el => (
<p key={el}>{el}: {el === "isSupported" ? status.isSupported ? "Yes" : "No": status[el as keyof typeof status]}</p>
))
}
</div>)
}Types
BatteryStatus
Reactive state snapshot of the device's battery, returned by useBattery. All properties are updated automatically via Battery Status API events.
| Property | Type | Required | Description |
|---|---|---|---|
isSupported | boolean | ✓ | true when the Battery Status API is available in the current browser/environment. |
level | number | ✓ | Current battery charge level as a value between 0.0 (empty) and 1.0 (full). Multiply by 100 to get a percentage. |
charging | boolean | ✓ | true when the battery is currently being charged. |
chargingTime | number | ✓ | Estimated seconds remaining until the battery is fully charged. Infinity when the battery is not charging or the time cannot be determined. |
dischargingTime | number | ✓ | Estimated seconds of remaining battery life. Infinity when the battery is charging or the time cannot be determined. |
UseBatteryProps
Configuration object accepted by useBattery.
All callback properties mirror the Battery Status API events. They are optional — omit any you don't need.
| Property | Type | Required | Description |
|---|---|---|---|
onCharging | (evt: Event) => void | Called when the battery's charging state changes (i.e. the charger is plugged in or unplugged). | |
onChargingTime | (evt: Event) => void | Called when the estimated time until the battery is fully charged changes. | |
onDischargingTime | (evt: Event) => void | Called when the estimated remaining battery life changes. | |
onLevel | (evt: Event) => void | Called when the battery level changes. |
