Created
September 16, 2019 13:23
-
-
Save damncabbage/87b3178d25c9c26c18801d828d36f4ac to your computer and use it in GitHub Desktop.
A hook that provides a flag to be used in promises and other async functions that can be triggered and not yet resolved by the time a component unmounts.
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
// @flow | |
import { useEffect, useRef } from 'react'; | |
// A hook that provides a flag to be used in promises and other async functions that | |
// can be triggered and not yet resolved by the time a component unmounts. | |
// | |
// For example: | |
// | |
// const isMounted = useUnmountCanary(); | |
// | |
// const saveNewTitle = title => { | |
// setLoading(true); | |
// return saveTitleMutation({ variables: { title }) | |
// .then(x => { | |
// // Calling setLoading() after the component has been unmounted will | |
// // make React throw a big nasty console error. This just avoids | |
// // setLoading()-ing if the component is no longer around to care. | |
// if (isMounted) setLoading(false); | |
// }); | |
// }; | |
// | |
// return <button onClick={() => saveNewTitle("Example!")} />; | |
// | |
export default function useUnmountCanary(): boolean { | |
const isMounted = useRef(true); | |
useEffect(() => { | |
return () => { | |
isMounted.current = false; | |
}; | |
}, []); | |
return isMounted.current; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment