useBattery
Track the battery status of a user’s device with useBattery.
Install:
npm i @uidotdev/usehooks
Description:
The useBattery hook is useful for accessing and monitoring the battery status of the user’s device in a React application. By using this hook, you can easily retrieve information such as the battery level, charging status, and estimated charging and discharging times. It provides a state object that includes properties like supported, loading, level, charging, chargingTime, and dischargingTime.
Return Values
The hook returns an object containing the following properties:
Name | Type | Description |
---|---|---|
supported | boolean | Indicates whether the Battery Status API is supported in the user’s browser. |
loading | boolean | Indicates if the battery information is still loading. |
level | number | Represents 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. |
charging | boolean | Represents whether the system’s battery is charging. true means the battery is charging, false means it’s not. |
chargingTime | number | Represents the time remaining in seconds until the system’s battery is fully charged. |
dischargingTime | number | Represents the time remaining in seconds until the system’s battery is completely discharged and the system is about to be suspended. |
Demo:
Example:
import { useBatttery } from "@uidotdev/usehooks";
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>
</>
);
}