Cleanup function là function được return từ useEffect, chạy trước khi effect chạy lại hoặc component unmount.
Dùng để hủy subscriptions, clearTimeout, cancel fetch requests tránh memory leaks và stale updates.
tsx
useEffect(() => {
const timer = setInterval(() => {
setCount(c => c + 1)
}, 1000)
const subscription = eventSource.subscribe(handler)
// cleanup: chạy khi unmount hoặc trước khi effect chạy lại
return () => {
clearInterval(timer)
subscription.unsubscribe()
}
}, [])The cleanup function is the function returned from useEffect.
- It runs before the effect re-runs or before the component unmounts.
- Use it to cancel subscriptions, clear timeouts, or abort fetch requests to prevent memory leaks and stale updates.
tsx
useEffect(() => {
const timer = setInterval(() => {
setCount(c => c + 1)
}, 1000)
const subscription = eventSource.subscribe(handler)
// cleanup: runs on unmount or before re-running the effect
return () => {
clearInterval(timer)
subscription.unsubscribe()
}
}, [])