Skip to content

Commit 6e3548f

Browse files
refactor: optimized usIsMounted hook
1 parent 1aab87d commit 6e3548f

File tree

1 file changed

+10
-7
lines changed

1 file changed

+10
-7
lines changed
Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,18 @@
11
import { useEffect, useRef } from 'react';
22

33
export const useIsMountedRef = () => {
4-
const isMounted = useRef<boolean | null>(null);
4+
// Initial value has been set to true, since this hook exist only for sole purpose of
5+
// avoiding any setState calls (within async operation) after component gets unmounted.
6+
// Basically we don't need to know about state change from component being initialized -> mounted.
7+
// We only need a state change from initialized or mounted state -> unmounted state.
8+
const isMounted = useRef(true);
59

6-
useEffect(() => {
7-
isMounted.current = true;
8-
9-
return () => {
10+
useEffect(
11+
() => () => {
1012
isMounted.current = false;
11-
};
12-
}, []);
13+
},
14+
[],
15+
);
1316

1417
return isMounted;
1518
};

0 commit comments

Comments
 (0)