Skip to content

Commit cecddf0

Browse files
fix(useBattery): prevent state update and memory leak on unmount
Add mounted flag to handle cleanup when component unmounts before getBattery() promise resolves. This prevents setState calls on unmounted components and avoids registering event listeners that would never be cleaned up.
1 parent 243087f commit cecddf0

File tree

1 file changed

+7
-1
lines changed

1 file changed

+7
-1
lines changed

src/useBattery/index.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,15 +96,20 @@ export function useBattery(): UseBatteryState {
9696
}
9797

9898
let battery: BatteryManager | null = null;
99+
let mounted = true;
99100

100101
const handleChange = () => {
101-
if (battery) {
102+
if (battery && mounted) {
102103
setState(getBatteryState(battery));
103104
}
104105
};
105106

106107
// eslint-disable-next-line @typescript-eslint/no-floating-promises,promise/catch-or-return,promise/prefer-await-to-then,promise/always-return
107108
nav.getBattery().then((b) => {
109+
if (!mounted) {
110+
return;
111+
}
112+
108113
battery = b;
109114
setState(getBatteryState(battery));
110115

@@ -115,6 +120,7 @@ export function useBattery(): UseBatteryState {
115120
});
116121

117122
return () => {
123+
mounted = false;
118124
if (battery) {
119125
off(battery, 'chargingchange', handleChange);
120126
off(battery, 'chargingtimechange', handleChange);

0 commit comments

Comments
 (0)