import { useState, useEffect } from 'react';
import { DeviceInfoModule } from 'react-native-nitro-device-info';
import { isLowBatteryLevel } from './utils';
/**
* Monitor for low battery conditions.
*
* Returns the battery level only when it drops below the platform-specific threshold:
* - iOS: 20% (matches iOS low power mode trigger)
* - Android: 15% (matches Android low battery warning)
*
* When the battery is above the threshold or unavailable, returns null.
*
* @returns Battery level when low, or null if not low or unavailable
*
* @example
* ```tsx
* import { useBatteryLevelIsLow } from 'react-native-nitro-device-info';
*
* function LowBatteryWarning() {
* const lowBattery = useBatteryLevelIsLow();
*
* if (lowBattery !== null) {
* return (
*
* Low Battery: {Math.round(lowBattery * 100)}%
*
* );
* }
*
* return null;
* }
* ```
*
* @platform iOS, Android
*/
export function useBatteryLevelIsLow(): number | null {
const [batteryLevelIsLow, setBatteryLevelIsLow] = useState(
null
);
useEffect(() => {
const checkBatteryLevel = () => {
const level = DeviceInfoModule.getBatteryLevel();
const newValue = isLowBatteryLevel(level) ? level : null;
setBatteryLevelIsLow(prev => prev === newValue ? prev : newValue);
};
checkBatteryLevel();
// Poll for changes (no throttle for low battery alerts - important to detect quickly)
const intervalId = setInterval(checkBatteryLevel, 2000);
return () => {
clearInterval(intervalId);
};
}, []);
return batteryLevelIsLow;
}