An Elegant Way to Reuse Code

After this lesson you will be able to pull repeated logic out of components into composables - plain functions that own reactive state, wire up lifecycle hooks and clean up after themselves. You will know why ref and reactive behave differently when you destructure them, when to use watch and when to use watchEffect, and how to make sure a composable can be used twice on the same page without the two instances sharing state.

What a composable is

A composable is a function that uses Vue’s reactivity and lifecycle APIs to encapsulate a piece of stateful logic. By convention its name starts with use, which is what makes composables recognisable at a call site.

// useToggle.js
import { ref } from 'vue';

export function useToggle(initialValue = false) {
  const isOn = ref(initialValue);

  function toggle() {
    isOn.value = !isOn.value;
  }

  return { isOn, toggle };
}
<script setup>
import { useToggle } from './useToggle';

const { isOn, toggle } = useToggle();
</script>

<template>
  <button type="button" @click="toggle">
    {{ isOn ? 'On' : 'Off' }}
  </button>
</template>

What makes this better than copying the three lines into every component is not the line count. It is that the contract is now explicit: the component asks for a toggle and gets a boolean plus an action. When the behaviour later needs a third piece of state - a timestamp of the last flip, say - only the composable changes.

Composables are not limited to components. They can be called from a router guard, from a Pinia store setup function, or from another composable, as long as they are called inside an active effect scope.

ref against reactive

Both create reactive state, and choosing the wrong one is the most common source of Vue confusion.

import { ref, reactive } from 'vue';

const count = ref(0);                 // a single value, wrapped in a box
const state = reactive({ user: {} }); // an object, returned as a proxy
Aspectrefreactive
HoldsAny value, including primitivesObjects and arrays only
Accesscount.valuestate.user
ReassignmentAllowedNot allowed - reassigning the variable replaces the proxy and breaks reactivity
DestructuringLoses reactivity unless you keep the ref itselfLoses reactivity immediately
Returned from a composableSafe, because the caller gets a refUnsafe, because the caller gets a plain object

The last row is the practical difference. A composable that returns a reactive object hands the caller a snapshot of the object’s properties at the moment of destructuring - and the same is true of a ref, because ref only auto-unwraps in templates and in the returned object of a store, not in plain destructuring.

// Broken: `count` is a plain number from now on.
const { count } = reactive({ count: 0 });

// Broken for the same reason.
const { count } = ref(0);

Two fixes exist. The modern one is to return the ref itself and let the caller unwrap it:

export function useCounter() {
  const count = ref(0);
  const doubled = computed(() => count.value * 2);

  return { count, doubled };
}
<script setup>
const { count, doubled } = useCounter();
</script>

<template>
  <!-- `count` is unwrapped automatically in the template -->
  <p>{{ count }} / {{ doubled }}</p>
</template>

The classic fix is toRefs, which turns the properties of a reactive object into refs: const { count, name } = toRefs(state). Both values stay in sync with state.

A third option, toValue, normalises the three shapes a reactive input can take - a raw value, a ref, or a getter function - into a plain value. It is the tool to reach for when a composable should accept any of them: watch(() => toValue(props.userId), loadUser).

Lifecycle hooks inside composables

Lifecycle hooks work inside a composable as long as the composable is called during a component’s setup. This is what lets a composable own a subscription.

// useMouse.js
import { ref, onMounted, onUnmounted } from 'vue';

export function useMouse(target) {
  const x = ref(0);
  const y = ref(0);

  function handleMove(event) {
    x.value = event.clientX;
    y.value = event.clientY;
  }

  onMounted(() => {
    const element = target ?? window;
    element.addEventListener('mousemove', handleMove);
  });

  onUnmounted(() => {
    const element = target ?? window;
    element.removeEventListener('mousemove', handleMove);
  });

  return { x, y };
}

Two rules keep this safe:

  1. Always pair an onMounted subscription with an onUnmounted removal. Otherwise the handler keeps a reference to a destroyed component.
  2. Register the hooks synchronously during setup. A hook called after an await inside setup belongs to no active component, and Vue warns that the hook was called without an active instance.

When a composable may be used outside a component - in a store, or detached from any component - use onScopeDispose instead, which fires when the surrounding effect scope is disposed.

import { onScopeDispose } from 'vue';

export function useDetachedTimer(callback, interval) {
  const id = setInterval(callback, interval);
  onScopeDispose(() => clearInterval(id));
}

effectScope groups several reactive effects so they can be stopped together, which is what you want in a test: create a scope, call scope.run(() => { ... }) to build the effects inside it, and call scope.stop() to dispose them all at once.

watch against watchEffect

Both react to change. They differ in what they react to and when they run.

watch is explicit. You name the source and the callback:

import { ref, watch } from 'vue';

const query = ref('');
const results = ref([]);

watch(query, async (newValue) => {
  if (newValue.length < 3) {
    results.value = [];
    return;
  }
  results.value = await search(newValue);
});

watchEffect is implicit. It runs immediately and re-runs whenever any reactive value it read changes:

watchEffect(async () => {
  if (query.value.length < 3) {
    results.value = [];
    return;
  }
  results.value = await search(query.value);
});

Pick watch when you want the previous and next values, when the callback should run only on a specific source, or when you want to keep an expensive computation from running until a dependency actually changes. Pick watchEffect when the set of dependencies is obvious from the body and you do not care about the old value.

Options that matter

immediate: true runs the callback once, right away. deep: true makes a watcher react to mutations inside a plain object or array - it works by traversing the value, which means it is expensive for large structures, so watching a specific getter such as () => form.user.email is usually cheaper. flush controls when the callback runs relative to the render: pre is the default and runs before the component re-renders, post runs after the render and is what you want when the callback must measure the updated DOM, and sync runs the callback immediately on every mutation, with no scheduling at all.

onCleanup gives you a hook to cancel work that is no longer needed - a stale network response, a pending timer.

watch(query, async (value, _oldValue, onCleanup) => {
  const controller = new AbortController();
  onCleanup(() => controller.abort());

  results.value = await search(value, { signal: controller.signal });
});

Both watch and watchEffect return a stop handle, and both can be stopped automatically by registering the handle with onScopeDispose.

Returning state without breaking it

The rule for a composable’s return value: return refs and functions, never a plain reactive object.

// Good: the caller can destructure and keep reactivity.
export function useProfile() {
  const user = ref(null);
  const loading = ref(false);

  async function load(id) {
    loading.value = true;
    user.value = await fetchUser(id);
    loading.value = false;
  }

  return { user, loading, load };
}

Returning state where state is a reactive object is the wrong version: the caller destructures it and loses reactivity. If you want to expose a reactive object, hand it over through toRefs, or keep the object in a ref and expose a readonly view of it.

Pitfalls to remember

  • Destructuring a reactive object, or a ref, breaks reactivity. Return the ref.
  • A composable called twice must create two independent states. Do not put a ref at module scope, or every caller shares it.
  • Lifecycle hooks must be registered synchronously during setup.
  • deep: true traverses the whole value on every change; watch a getter when you only care about one property.
  • A watcher on a promise-returning callback can deliver stale results. Use onCleanup to cancel superseded work.

Practice

Two unrelated screens - a search page and a filter panel - both need to talk to the same backend with the same rules: a request is only sent once the query is at least three characters long, requests older than the newest one are discarded, and the loading flag is cleared when the request finishes.

Write the composable, then show how the search page would use it.

Vue 3ComposableswatchwatchEffectCleanup

Approach:

The rules are the same in both places, so they belong in one composable. The composable owns the query, the results and the loading flag, and it uses watch rather than watchEffect because the source is a single explicit value and the callback needs to decide whether to run at all. The stale-response problem is solved with onCleanup and an AbortController.

Steps:

  1. Accept the query from the caller. The composable exposes a query ref so the caller can bind an input to it, and the watcher watches that ref.
  2. Guard inside the callback. If the query is shorter than three characters, clear the results and return without sending a request.
  3. Cancel superseded requests. Register an AbortController through onCleanup. When the query changes again, Vue calls the previous cleanup function, which aborts the in-flight request.
  4. Always clear the loading flag. Use try and finally so an aborted or failed request does not leave the flag stuck at true.
  5. Return refs, not a plain object. The caller destructures query, results and loading and keeps reactivity.

Answer:

// useSearch.js
import { ref, watch } from 'vue';

export function useSearch(minLength = 3) {
  const query = ref('');
  const results = ref([]);
  const loading = ref(false);
  const error = ref(null);

  watch(query, async (value, _oldValue, onCleanup) => {
    const term = value.trim();

    if (term.length < minLength) {
      results.value = [];
      error.value = null;
      return;
    }

    const controller = new AbortController();
    onCleanup(() => controller.abort());

    loading.value = true;
    error.value = null;

    try {
      const response = await fetch(
        `/api/search?q=${encodeURIComponent(term)}`,
        { signal: controller.signal },
      );
      results.value = await response.json();
    } catch (err) {
      if (err.name !== 'AbortError') {
        error.value = err;
      }
    } finally {
      loading.value = false;
    }
  });

  return { query, results, loading, error };
}

The search page calls useSearch, binds query to an input with v-model, renders results as a list, and shows loading and error when they are set.

The filter panel calls useSearch as well and gets its own independent query, results and loading state, because everything lives inside the function body rather than at module scope.

Found an issue with this content?

Tell us what could be improved.