1 | import { useRef, useEffect } from 'react';
|
2 | /**
|
3 | * Track whether a component is current mounted. Generally less preferable than
|
4 | * properlly canceling effects so they don't run after a component is unmounted,
|
5 | * but helpful in cases where that isn't feasible, such as a `Promise` resolution.
|
6 | *
|
7 | * @returns a function that returns the current isMounted state of the component
|
8 | *
|
9 | * ```ts
|
10 | * const [data, setData] = useState(null)
|
11 | * const isMounted = useMounted()
|
12 | *
|
13 | * useEffect(() => {
|
14 | * fetchdata().then((newData) => {
|
15 | * if (isMounted()) {
|
16 | * setData(newData);
|
17 | * }
|
18 | * })
|
19 | * })
|
20 | * ```
|
21 | */
|
22 |
|
23 | export default function useMounted() {
|
24 | var mounted = useRef(true);
|
25 | var isMounted = useRef(function () {
|
26 | return mounted.current;
|
27 | });
|
28 | useEffect(function () {
|
29 | mounted.current = true;
|
30 | return function () {
|
31 | mounted.current = false;
|
32 | };
|
33 | }, []);
|
34 | return isMounted.current;
|
35 | } |
\ | No newline at end of file |