Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 87 ยท Lifecycle and Composition API

Composable Patterns

Practical Vue composable patterns - a useFetch that handles races, useDebounce, a storage-backed ref, flexible inputs with toValue and MaybeRefOrGetter, and cleanup with onScopeDispose.

You now know what a composable is: a useX function that owns some reactive state and returns it. This lesson collects the patterns you will write again and again in real projects: loading data, debouncing a value, keeping state in storage, accepting flexible inputs, and cleaning up in a way that works inside and outside components.

Every example here runs in the sandbox. That has two consequences. There is no network, so the data composable talks to a small fake server built with timers. And localStorage throws inside the preview, so the storage composable receives its storage object as a parameter and we pass an in-memory stand-in. That second point is also good design: a composable that takes its dependencies as arguments is easy to test.

Flexible inputs with toValue

Suppose a composable needs a URL. Callers might have a constant string, a ref, or a computed value. You can accept all three with one helper, toValue, available since Vue 3.3. It reads a plain value as is, unwraps a ref and calls a getter function.

JavaScript
import { ref, toValue } from "vue";

toValue("/users/1");            // "/users/1"
toValue(ref("/users/1"));       // "/users/1"
toValue(() => "/users/" + id.value);  // calls the getter

The type that describes "any of those three" is called MaybeRefOrGetter. In a TypeScript project you write it like this (read-only here, because the runner has no TypeScript for Vue):

TypeScript
import type { MaybeRefOrGetter } from "vue";

function useFetch(url: MaybeRefOrGetter<string>) {
  // toValue(url) always gives a string
}

There is a similar type, MaybeRef<T> (a value or a ref, no getters), which pairs with unref. Prefer toValue for inputs of new composables, because the getter form () => "/users/" + id.value is concise and always reactive. When you call toValue inside watchEffect, watch or computed, the read is tracked, so the work reruns when the input changes.

flowchart LR
    A["plain value"] --> T["toValue(input)"]
    B["ref"] --> T
    C["getter function"] --> T
    T --> E["watchEffect<br/>reruns when input changes"]
    E --> S["data, error, loading refs"]

Three kinds of input, one normalization step, one reactive effect.

useFetch with loading, error and race protection

A data composable returns three refs (data, error, loading) and refetches when its input changes. The tricky part is the race: if the user clicks "load 1" and then "load 2", and the first request is slower, its answer arrives after the second and would overwrite the newer result. watchEffect gives its callback an onCleanup function that runs before the effect reruns, which is exactly where you mark the old request as stale.

useFetch with a fake server and race protection

On load the page requests user 1, which takes 0.4 seconds. Press "Load user 2" right away: user 2 answers after 0.1 seconds and is shown. When the slow answer for user 1 finally arrives, the composable recognizes it as stale, throws it away and the counter goes to 1, while the page keeps showing user 2. Press "Load user 3" to see the error branch.

Notice what the caller wrote: useFetch(() => "/users/" + id.value). A getter, no manual watching, no cleanup code. All the hard parts are inside the composable. A production version would use fetch with an AbortController (call controller.abort() in the same onCleanup) so the browser also cancels the request. Fetching data covers the full approach.

useDebounce

Typing in a search box can fire an update per keystroke. A debounced value only changes after the input has been quiet for a moment. The composable watches a source, restarts a timer on each change and exposes a second ref that lags behind.

useDebounce for a search box

Type "pin" quickly: "You typed" updates at every key, but "Settled value" and the search counter only change once, about 0.4 seconds after you stop, and the list narrows to "pineapple". The onScopeDispose line makes sure a pending timer does not fire after the component has gone. We will return to it below.

A storage-backed ref

Another favorite is a ref that saves itself. The idea: read the saved value at creation, write on every change. In a real page you pass localStorage:

JavaScript
// Real browser code (read-only here: localStorage throws inside the sandbox)
export function useLocalStorage(key, initial) {
  let stored = null;
  try {
    stored = window.localStorage.getItem(key);
  } catch {
    // storage blocked or unavailable: fall back to the initial value
  }
  const state = ref(stored === null ? initial : JSON.parse(stored));

  watch(state, (value) => {
    try {
      window.localStorage.setItem(key, JSON.stringify(value));
    } catch {
      // quota exceeded or blocked: ignore
    }
  }, { deep: true });

  return state;
}

The try/catch blocks matter: storage can be disabled, full or blocked in private windows. Here is the same idea with the storage passed in, so it runs in the preview. The stand-in is a reactive object so the page can show what was "saved".

A useStorage composable with an in-memory store

Edit the note, press "Unmount", then "Mount": the text is still there, because the new component instance read it back from the store before creating its ref. The saved store line shows the JSON string the composable wrote.

Async composables

A composable cannot simply be async. Components call composables synchronously during setup(), and an async function would hand back a promise instead of refs and would lose the current component instance for any hooks registered after an await. The usual pattern is the one useFetch used: return the refs immediately, fill them in later, and (if callers need to wait) also return a promise.

JavaScript
export function useUser(id) {
  const user = ref(null);
  const ready = loadUser(toValue(id)).then((result) => {
    user.value = result;
  });
  return { user, ready };
}

Most callers just read user and let the template handle the null case; a caller that must wait can await ready in code that does not depend on the component instance.

Cleanup with onScopeDispose

onUnmounted only works while a component is the current instance. What if a composable runs somewhere else: in a test, in a shared store, or in a function you call outside any component? The primitive underneath is the effect scope. Every component has one; it collects the watchers and computed values created during setup and stops them when the component unmounts. onScopeDispose(callback) registers a function to run when the current scope stops. Inside a component that means "when the component is unmounted", so it works there too.

You can create scopes yourself with effectScope(). This example starts a ticking composable inside a manual scope and stops the whole scope with one call.

effectScope and onScopeDispose without a component

After "Start scope" the tick count climbs about ten times per second. "Stop scope" stops the watcher, runs the onScopeDispose callback (clearing the interval) and the number freezes. The event list reads "scope started", "ticker cleaned up", "scope stopped": the dispose callback runs inside scope.stop(), before the line that follows it.

flowchart TB
    SC["effectScope or component scope"] --> W["watchers"]
    SC --> CM["computed values"]
    SC --> D["onScopeDispose callbacks"]
    ST["scope.stop() or unmount"] --> SC
    ST -.->|"stops"| W
    ST -.->|"stops"| CM
    ST -.->|"runs"| D

Stopping a scope stops everything created inside it and runs its dispose callbacks.

Libraries such as VueUse use onScopeDispose for every cleanup for exactly this reason. In your own composables, choose it over onUnmounted whenever the composable might run outside a component. Its limit is that it needs an active scope: calling it with no scope prints a warning in development builds.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does toValue(input) do when input is a function?

    toValue reads plain values as they are, unwraps refs, and calls getter functions. That is why it can accept all three kinds of input.
  2. 2. Why does useFetch mark the previous request as stale inside onCleanup?

    A slow old request can finish after a fast new one. The stale flag lets the composable ignore that late answer.
  3. 3. Why does useStorage in the runnable example take the storage object as a parameter?

    The preview runs in an opaque-origin sandbox where localStorage throws. Injecting the storage lets the demo use an in-memory stand-in, and tests can do the same.
  4. 4. When is onScopeDispose a better choice than onUnmounted?

    onUnmounted needs a component instance. onScopeDispose works with any effect scope, including the scope of a component, so it covers both situations.
  5. 5. Why should a composable not be declared async?

    Components call composables synchronously during setup. Return the refs right away, fill them later, and expose a promise separately if callers need one.

Summary

  • toValue and the MaybeRefOrGetter type let one parameter accept a value, a ref or a getter; read it inside an effect so the work reruns on change.
  • A data composable returns data, error and loading refs and uses watchEffect with onCleanup to ignore stale responses.
  • useDebounce watches a source and exposes a second ref that settles after a quiet period.
  • Storage-backed refs read once, write in a deep watcher, wrap storage calls in try/catch, and take the storage as a parameter for testing.
  • Composables stay synchronous: return refs now, fill them later, and return a promise separately if needed.
  • onScopeDispose registers cleanup for the current effect scope, which works inside components and in manual effectScope() calls.

Up next, a look at the older way of writing components that you will still meet in many codebases: The Options API.