Skip to content

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.

PropertyTypeRequiredDescription
isSupportedboolean✓true when the Battery Status API is available in the current browser/environment.
levelnumber✓Current battery charge level as a value between 0.0 (empty) and 1.0 (full). Multiply by 100 to get a percentage.
chargingboolean✓true when the battery is currently being charged.
chargingTimenumber✓Estimated seconds remaining until the battery is fully charged. Infinity when the battery is not charging or the time cannot be determined.
dischargingTimenumber✓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.

PropertyTypeRequiredDescription
onCharging(evt: Event) => voidCalled when the battery's charging state changes (i.e. the charger is plugged in or unplugged).
onChargingTime(evt: Event) => voidCalled when the estimated time until the battery is fully charged changes.
onDischargingTime(evt: Event) => voidCalled when the estimated remaining battery life changes.
onLevel(evt: Event) => voidCalled when the battery level changes.

Released under the MIT License.