Vue Tip: Manually Stop Watcher
Vue automatically stops watchers (watch
and watchEffect
) when the component is unmounted if they are created synchronously in <script setup>
or setup()
.
The following watcher will automatically be stopped if Component.vue
is unmounted:
However, if you create a watcher asynchronously, it will not be stopped automatically:
In this case, you can manually stop the watcher by calling the stop
function that is returned by watchEffect
:
Note
You should prefer creating watchers synchronously and only in rare cases create them asynchronously.
Unstopped watchers can lead to memory leaks and unexpected behavior.
In our example, we could create the watcher synchronously and watch the user
ref instead:
This way, the watcher is automatically stopped and you don't need to worry about stopping the watcher yourself.
If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Vue Tip: Dynamic Return Values in Composables
FIXME
Vue Tip: Simple State Management With Composition API
Learn how you can use Composition API for a simple state management solution which you can use instead of Pinia.