Last active
March 8, 2019 21:26
-
-
Save mfunkie/711d900fa39e0b7d00f66574d0e80d58 to your computer and use it in GitHub Desktop.
Invoke a callback only on unmount of the component
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
import React, { useEffect, useRef } from 'react' | |
// usage | |
function MyComponent() { | |
const { cleanupReduxStateWithSavedIDSoModalDoesntCloseNextTimeItIsOpened, savedID } = props | |
useEffect(() => { | |
if (savedID) { | |
// onSuccess could be doing something where in other areas savedID is still pulled from a redux store | |
onSuccess(savedID) | |
} | |
}, [savedID, onSuccess]) | |
useCallOnUnmount(() => cleanupReduxStateWithSavedIDSoModalDoesntCloseNextTimeItIsOpened()) | |
// irrelevant stuff | |
return <div /> | |
} | |
function useCallOnUnmount(callback: () => mixed) { | |
const savedCallback = useRef(callback) | |
useEffect(() => { | |
savedCallback.current = callback | |
}) | |
useEffect(() => { | |
function invokeCallback() { | |
if (savedCallback.current) { | |
savedCallback.current() | |
} | |
} | |
return () => { | |
invokeCallback() | |
} | |
}, []) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment