Skip to content

Instantly share code, notes, and snippets.

@ccnokes
Last active April 6, 2020 16:38
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 ccnokes/0d45607001aa88b3be7b7efae11e5910 to your computer and use it in GitHub Desktop.
Save ccnokes/0d45607001aa88b3be7b7efae11e5910 to your computer and use it in GitHub Desktop.
React hook that only runs a function if the component is still mounted. React says this is an anti-pattern, but vanilla Promises and async DOM APIs don't give you a way to cancel async actions 🤷‍♂️.
function useCallIfMounted() {
let isMounted = React.useRef(false);
React.useEffect(() => {
isMounted.current = true;
return () => isMounted.current = false;
}, [isMounted]);
return React.useCallback((fn) => isMounted.current && fn(), [isMounted]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment