useBattery
Monitor device battery status in real-time with TypeScript support. Provides battery level, charging status, and time estimates with automatic updates.
Interactive Demo
Battery API is not supported in this browser
Implementation
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-explicit-any */
// typescript don't include navigator.getBattery in the type
interface Navigator {
getBattery(): Promise<any>;
}
declare global {
interface Navigator {
getBattery(): Promise<any>;
}
}
interface BatteryState {
charging: boolean;
level: number;
chargingTime: number | null;
dischargingTime: number | null;
supported: boolean;
error: string | null;
}
const initialState: BatteryState = {
charging: false,
level: 0,
chargingTime: null,
dischargingTime: null,
supported: false,
error: null,
};
export function useBattery() {
const [batteryState, setBatteryState] = useState<BatteryState>(initialState);
useEffect(() => {
// Check if running in a secure context (HTTPS)
if (typeof window !== "undefined" && !window.isSecureContext) {
setBatteryState((prev) => ({
...prev,
supported: false,
error: "Battery API requires a secure context (HTTPS)",
}));
return;
}
const getBatteryInfo = async () => {
if (!navigator?.getBattery) {
setBatteryState((prev) => ({
...prev,
supported: false,
error: "Battery API is not supported in this browser",
}));
return;
}
try {
const battery = await navigator.getBattery();
const updateBatteryInfo = () => {
setBatteryState({
charging: battery.charging,
level: Math.floor(battery.level * 100),
chargingTime: battery.chargingTime !== Infinity ? battery.chargingTime : null,
dischargingTime: battery.dischargingTime !== Infinity ? battery.dischargingTime : null,
supported: true,
error: null,
});
};
// Initial update
updateBatteryInfo();
// Add event listeners
battery.addEventListener("chargingchange", updateBatteryInfo);
battery.addEventListener("levelchange", updateBatteryInfo);
battery.addEventListener("chargingtimechange", updateBatteryInfo);
battery.addEventListener("dischargingtimechange", updateBatteryInfo);
// Cleanup
return () => {
battery.removeEventListener("chargingchange", updateBatteryInfo);
battery.removeEventListener("levelchange", updateBatteryInfo);
battery.removeEventListener("chargingtimechange", updateBatteryInfo);
battery.removeEventListener("dischargingtimechange", updateBatteryInfo);
};
} catch {
setBatteryState((prev) => ({
...prev,
supported: false,
error: "Failed to access battery information",
}));
}
};
getBatteryInfo();
}, []);
return batteryState;
}
Usage Examples
import { useBattery } from '@/components/hooks/useBattery';
function BatteryStatus() {
const { charging, level, supported } = useBattery();
if (!supported) {
return <div>Battery API not supported</div>;
}
return (
<div>
<div>Battery Level: {level}%</div>
<div>Status: {charging ? 'Charging' : 'Not charging'}</div>
</div>
);
}
Documentation
Key Features
- Real-time battery status monitoring
- Charging state detection
- Battery level percentage
- Charging and discharging time estimates
- Browser compatibility detection
- TypeScript support
Common Use Cases
- Battery status indicators
- Power-saving mode triggers
- Battery-aware feature adjustments
- Device energy monitoring
- Low battery notifications
API Reference
useBattery(): BatteryState
Returns the current battery state.
Return value:
- charging: boolean - Whether the device is currently charging
- level: number - Battery level as a percentage (0-100)
- chargingTime: number - Seconds until battery is fully charged
- dischargingTime: number - Seconds until battery is empty
- supported: boolean - Whether the Battery API is supported
Browser Compatibility
The Battery Status API has limited browser support and requires a secure context (HTTPS). It is primarily supported in Chrome-based browsers.
Requirements:
- Secure context (HTTPS)
- Chrome/Chromium-based browsers
- Appropriate permissions policy
For more details, see the MDN documentation.