Skip to content

Instantly share code, notes, and snippets.

@VitorLuizC
Last active February 21, 2020 22:24
Show Gist options
  • Select an option

  • Save VitorLuizC/0714b920218a22031edfc77da8f5dbb4 to your computer and use it in GitHub Desktop.

Select an option

Save VitorLuizC/0714b920218a22031edfc77da8f5dbb4 to your computer and use it in GitHub Desktop.
React Hooks to be reused by any developer.
import { useCallback, useEffect, useRef } from 'react';
/**
* Hook that provides a safe way to check if component is mounted.
* @example
* const isMounted = useIsMounted();
* const [users, setUsers] = useState([]);
*
* useEffect(() => {
* fetchUsers().then(users => {
* if (isMounted()) setUsers(users);
* });
* }, []);
*/
const useIsMounted = () => {
const mountedRef = useRef<boolean | null>(true);
useEffect(() => () => {
mountedRef.current = false;
}, []);
const isMounted = useCallback(() => mountedRef.current, []);
return isMounted;
};
export default useIsMounted;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment