Component Will Unmount React Hook
We can use the React.useEffect
hook cleanup cycle to implement this.
function useComponentWillUnmount(cleanupCallback = () => {}) {
const callbackRef = React.useRef(cleanupCallback)
callbackRef.current = cleanupCallback // always up to date
React.useEffect(() => {
return () => callbackRef.current()
}, [])
}
Because there are no dependencies in this effect, the cleanupCallback
will only be executed when the component will be unmounted and not on every render.
Notice that we need to use a reference to the callback in case the component re-renders and the callback changes. This has essentially three benefits
- we don’t need to keep a state inside our custom hook
- we don’t need to add dependencies to the
React.useRef
- parent components do not need to worry about
React.useCallback
optimization to avoid re-rendering.
Side Effects
Be careful with state changes on unmounted components. You can update state on parent components which are still mounted and you can do so by passing some prop into the component to notify the parent component when it unmounts.
Usage
function MyComponent({ onUnmount }) {
useComponentWillUnmount(onUnmount)
return ...
}