react-use/src/useMountedState.ts
xobotyi 5350e8d9ee useMountedState as a replacement for useRefMounted:
- it has more obvious name;
 - returns a function that check mount state -> more handy ti use due to less to write;
 - has tests;
2019-07-31 00:05:12 +03:00

16 lines
305 B
TypeScript

import { useEffect, useRef } from 'react';
export default function useMountedState(): () => boolean {
const mountedRef = useRef<boolean>(false);
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
};
});
return () => mountedRef.current;
}