0 day streak
javascript / intermediate
Snippet

Side-Effect Cleanup in watchEffect

The watchEffect function receives an onCleanup callback that allows you to register logic to run before the effect is re-triggered or the component is unmounted. This is essential for preventing memory leaks from timers or event listeners.

snippet.js
javascript
1
2
3
4
watchEffect((onCleanup) => {
const timer = setInterval(() => console.log('Ping'), 1000);
onCleanup(() => clearInterval(timer));
});
vue
Breakdown
1
onCleanup(() => ...)
Registers a function that clears the interval when the dependency changes or the component is destroyed.