import { useCallback , useEffect , useState } from 'react' ; import { BatteryState , getBatteryStateAsync , addBatteryStateListener } from 'expo-battery' ; see https example export function useBatteryState ( options = { } ) { const [ data , setData ] = useState < BatteryState > ( ) ; const { get = true , listen = true , } = options ; const getBatteryState = useCallback ( ( ) => ( getBatteryStateAsync ( ) . then ( setData ) ) , [ ] ) ; useEffect ( ( ) => { if ( get ) { getBatteryState ( ) ; } if ( listen ) { return addBatteryStateListener ( state => setData ( state . batteryState ) ) . remove ; } } , [ get , getBatteryState , listen ] ) ; return [ data , getBatteryState ] ; } export interface BatteryStateOptions { /** If it should fetch the battery state when mounted, defaults to `true` */ get ? : boolean ; /** If it should listen to any change in battery state, defaults to `true` */ listen ? : boolean ; }