Skip to Content

useBattery

A hook that provides access to the device’s battery information through the Battery Status API. Perfect for implementing power-aware features and battery status indicators.

Parameters

This hook doesn’t take any parameters.

Returns

  • supported: boolean - Whether the Battery Status API is supported
  • loading: boolean - Whether the battery information is being fetched
  • level: number | null - Battery level from 0 to 1
  • charging: boolean | null - Whether the device is currently charging
  • chargingTime: number | null - Seconds until battery is fully charged
  • dischargingTime: number | null - Seconds until battery is fully discharged

Usage

import { useBattery } from '@rhinolabs/react-hooks'; function BatteryStatus() { const { supported, loading, level, charging, chargingTime, dischargingTime } = useBattery(); if (!supported) { return <div>Battery status not supported</div>; } if (loading) { return <div>Loading battery status...</div>; } return ( <div> <div>Battery Level: {(level! * 100).toFixed(0)}%</div> <div> Status: {charging ? 'Charging' : 'Not charging'} </div> {charging ? ( <div>Full charge in: {Math.round(chargingTime! / 60)} minutes</div> ) : ( <div>Time remaining: {Math.round(dischargingTime! / 60)} minutes</div> )} </div> ); }

Notes

  • Uses Battery Status API with browser support detection
  • Real-time updates with automatic state management
  • Type-safe nullability for all battery properties
  • Handles loading states and error boundaries
  • Implements automatic event listener cleanup
Last updated on