Skip to content

Instantly share code, notes, and snippets.

@mfunkie
Last active March 8, 2019 21:26
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 mfunkie/711d900fa39e0b7d00f66574d0e80d58 to your computer and use it in GitHub Desktop.
Save mfunkie/711d900fa39e0b7d00f66574d0e80d58 to your computer and use it in GitHub Desktop.
Invoke a callback only on unmount of the component
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