Last active
April 6, 2020 16:38
-
-
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 🤷♂️.
This file contains 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
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