Last active
February 21, 2020 22:24
-
-
Save VitorLuizC/0714b920218a22031edfc77da8f5dbb4 to your computer and use it in GitHub Desktop.
React Hooks to be reused by any developer.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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