Docs
Battery

Battery

Track the battery status of a user’s device.

About

The useBattery hook is a valuable tool for accessing and tracking the battery status of a user's device within a React application. This hook allows you to conveniently obtain details such as battery level, charging status, and estimated times for charging and discharging. It offers a state object that contains properties like supported, loading, level, charging, chargingTime, and dischargingTime.

Return Values

NameTypeDescription
supportedbooleanIndicates whether the Battery Status API is supported in the user’s browser.
loadingbooleanIndicates if the battery information is still loading.
levelnumberRepresents the level of the system’s battery. 0.0 means that the system’s battery is completely discharged, and 1.0 means the battery is completely charged.
chargingbooleanRepresents whether the system’s battery is charging. true means the battery is charging, false means it’s not.
chargingTimenumberRepresents the time remaining in seconds until the system’s battery is fully charged.
dischargingTimenumberRepresents the time remaining in seconds until the system’s battery is completely discharged and the system is about to be suspended.

Installation

Run the following command:

npx scriptkavi-hooks@latest add battery

Usage

import { useBattery } from "@/hooks/battery"
import Battery from "./Battery"
 
export default function App() {
  const { loading, level, charging, chargingTime, dischargingTime } =
    useBattery()
  return (
    <>
      <div className="wrapper">
        <h1>useBattery</h1>
        {!loading ? (
          <Battery
            level={level * 100}
            charging={charging}
            chargingTime={chargingTime}
            dischargingTime={dischargingTime}
          />
        ) : (
          <h2>Loading...</h2>
        )}
      </div>
    </>
  )
}