React patterns: Clean up effect when component unmounts
4 September 2022 (Updated 4 September 2022)
useEffect(() => {
const subscription = props.source.subscribe()
return () => {
// Clean up the subscription
subscription. Unsubscribe()
}
})
If you return a function from your useEffect
hook, React will call this function before the component is removed from the DOM. If a component re-renders (as they typically do), the previous effect is cleaned up before executing the next effect.
Image credit: donavan
Tagged:
React patterns