React patterns: Clean up effect when component unmounts
4 September 2022 (Updated 26 April 2024)
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
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment