Build Vue's effectScope(): nested and detached scopes, onScopeDispose, pause and resume, and a shared composable

hardAbout 50 minutesUpdated CodingProvuereactivityeffect-scopecomposablesmemory-leaks
Not solved

Share this question

Problem

Every component in Vue 3 owns an effect scope. The effects and watchers created during setup() attach to it, and unmounting the component stops the scope, which stops all of them at once. The same API is public as effectScope(), and libraries such as VueUse use it to run composables outside components without leaking watchers. Build it on top of the small reactivity core in the starter.

const scope = effectScope();
const count = ref(0);
scope.run(() => {
  watch(count, (n) => console.log("count", n));
  onScopeDispose(() => console.log("disposed"));
});
count.value = 1; // logs "count 1"
scope.stop(); // logs "disposed"
count.value = 2; // nothing: the watcher is stopped

Ref. UR-1460 · © UIRound · uiround.com/questions/build-vues-effectscope-nested-and-detached-scopes-onscopedispose-pause-and-resume-and-a-shared-composable

Stuck? Take a hint

Try it in the editor

Run your code as often as you like. Submitting it to the full test suite is part of Pro.

Private, and saved in this browser as you type. All your notes are on My lists.

Every question and answer7 days, one payment