Skip to content

Commit

Permalink
Fix useIsMounted
Browse files Browse the repository at this point in the history
  • Loading branch information
twschiller committed Nov 7, 2024
1 parent eb70a52 commit 73c1fe5
Showing 1 changed file with 10 additions and 7 deletions.
17 changes: 10 additions & 7 deletions src/hooks/useIsMounted.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,20 @@
import { useCallback, useEffect, useRef } from "react";

/**
* Returns a function that returns true if the component is still mounted.
* Returns a function that returns true if the component is mounted.
*/
// Reference implementation https://usehooks-ts.com/react-hook/use-is-mounted
function useIsMounted(): () => boolean {
const isMountedRef = useRef(true);
// Must start as false to support double-render/effect in strict mode
const isMountedRef = useRef(false);

useEffect(
() => () => {
useEffect(() => {
isMountedRef.current = true;

return () => {
isMountedRef.current = false;
},
[],
);
};
}, []);

return useCallback(() => isMountedRef.current, []);
}
Expand Down

0 comments on commit 73c1fe5

Please sign in to comment.