UNPKG

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