Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@damncabbage
Created September 16, 2019 13:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save damncabbage/87b3178d25c9c26c18801d828d36f4ac to your computer and use it in GitHub Desktop.
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.
// @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