Component Will Unmount React Hook

Pablo Garcia
1 min readSep 28, 2021

--

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

  1. we don’t need to keep a state inside our custom hook
  2. we don’t need to add dependencies to the React.useRef
  3. 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 ...
}

--

--

Pablo Garcia
Pablo Garcia

Written by Pablo Garcia

Senior Engineer at Netflix, ex-Staff Architect 2 at PayPal. M.S. in Computer Science w/specialization in Computing Systems. B.Eng. in Computer Software.

Responses (2)