Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 87 ยท Lifecycle and Composition API

Composables

Learn Vue composables - extract stateful logic into useX functions, pass refs in, return refs out, build useCounter and useMouse, and follow the conventions that keep composables predictable.

Components are Vue's tool for reusing UI. A composable is its tool for reusing logic that has state: a counter, a mouse-position tracker, a form field with validation. It is a plain JavaScript function that uses Vue's reactivity and lifecycle APIs and returns the reactive values and functions a component needs.

If you have read Lifecycle hooks, you already know the ingredients. A composable is just those ingredients (ref, computed, watch, onMounted, onUnmounted) wrapped in a function with a name that starts with use. This lesson shows how to extract one, how to pass reactive input, what to return, and which conventions make composables easy to read and hard to misuse.

Extracting logic into a function

Start with a component that owns a counter. All the counter logic is three things: a ref, a computed and two functions.

JavaScript
const count = ref(0);
const isEven = computed(() => count.value % 2 === 0);
const increment = () => { count.value++; };

Cut that code out, put it into a function, return what the component needs, and you have a composable.

A useCounter composable

The two counters share a recipe but not their numbers: pressing "+" next to Apples leaves Crates untouched. Each call to useCounter() creates a new ref, exactly as if you had pasted the three lines into each component. A composable shares logic, never state. (If you do want shared state, see Sharing state between components.)

Notice the template says apples.count.value. Returning a plain object keeps the refs inside it, and Vue only unwraps refs that sit at the top level of what setup() returns. The cleaner way is to destructure in the component, as the next section shows.

Return an object of refs

By convention a composable returns a plain object whose values are refs, computed values and functions. Not a reactive object, and not an array.

JavaScript
// a component using it
const { count, isEven, increment } = useCounter(5);

Destructuring works here because each property is a ref, and a ref keeps its reactivity when you copy it into a variable. If the composable had returned reactive({ count: 0 }), destructuring would copy a number and lose reactivity (see How reactivity works). Returning a plain object also lets the consumer rename things (const { count: apples } = useCounter()) and pick only what it needs.

If you want to return a reactive object anyway, wrap it with toRefs() when the caller destructures it, or return an object of refs from the start. The second option is what most Vue libraries do.

A composable with side effects: useMouse

The real power appears when a composable also owns setup and cleanup. A mouse-position tracker needs to add a listener when the component mounts and remove it when the component goes away. With a composable, that pairing lives in one place and no component can forget half of it.

flowchart LR
    C["Component"] -->|"calls in setup()"| U["useMouse()"]
    U --> R["x, y refs"]
    U --> M["onMounted: add listener"]
    U --> N["onUnmounted: remove listener"]
    R -->|"returned"| C

The composable owns the refs and the listener lifecycle; the component only reads x and y.

useMouse with automatic cleanup

Move the mouse over the preview and the numbers follow it. Press "Remove tracker" and the listener count drops from 1 to 0, proving the cleanup ran. If you mount two trackers at once the count would be 2, because each call to useMouse() registers its own listener. Everything the lifecycle lesson taught is inside the composable, so the component reads like a description of what it shows.

Accept refs as input

So far the inputs were plain numbers. Often a composable should react when its input changes, so it needs to receive a ref (or a computed) rather than a snapshot value.

A composable that reads a ref

The preview starts with "4 words, 20 characters, shortest word: Vue". Type in the textarea and all three values update, because useTextStats received the ref itself and its computed values depend on text.value. Had we passed draft.value (a string), the composable would have received a snapshot and never learned about later edits.

Accepting a ref is the rule when the value can change over time. Lesson Composable patterns introduces toValue, which lets one parameter be a plain value, a ref or a getter function, so callers can pass whichever is convenient.

Conventions

These habits keep composables predictable and are worth following from the start.

  1. Name it useSomething. The prefix tells readers (and linters) that the function uses reactivity or hooks, and should be called during setup().
  2. Call it at the top level of setup() or <script setup>, synchronously. Lifecycle hooks inside it attach to the component that is currently running setup, so calling it later, after an await or inside a timer, will not register them.
  3. Return an object of refs. Not a reactive object, so callers can destructure and rename.
  4. Take refs for values that change. Normalize input once at the top of the composable.
  5. Own your cleanup. If the composable starts something, stop it in onUnmounted.
  6. Keep it focused. useMouse tracks the mouse. A useEverythingAboutTheHeader function is a component's script in disguise.
  7. Put each composable in its own file, exported as a named function, for example composables/useMouse.js.

Composables can call other composables, so you can build larger behavior out of small pieces: a useSearch might use useDebounce and useFetch. Each piece stays testable on its own. The composables lesson of the testing chapter covers that (Testing composables and stores).

Composables replace mixins, the Vue 2 way of sharing logic. Mixins merged their properties into the component invisibly, which caused name clashes and made it hard to see where a value came from. With a composable, every value you use is visible in the destructuring line.

Composables or components?

A quick rule of thumb: if you are reusing something that has markup, make a component. If you are reusing behavior that has no markup of its own (tracking the mouse, formatting a value, debouncing input, managing a timer), make a composable. When both are needed, use both: a MouseTracker component can be a thin template over useMouse(). A related comparison with another framework appears in the React lesson on custom hooks, which solve the same problem.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Two components both call useCounter(). What happens to the count?

    Every call runs the function body again and creates new refs. A composable shares the logic, not the state.
  2. 2. Why do composables usually return an object of refs instead of a reactive object?

    A destructured ref is still a ref. Destructuring a reactive object copies plain values and breaks the connection.
  3. 3. A composable must react when the caller's input changes. How should the input be passed?

    Passing the ref itself lets the composable read ref.value later, so its computed values and watchers update. Passing .value gives it a one-time snapshot.
  4. 4. Where does a composable that registers onMounted need to be called?

    Lifecycle hooks attach to the component currently running its setup, so the composable has to be called synchronously from setup or script setup.

Summary

  • A composable is a useX function that uses Vue's reactivity and lifecycle APIs to package reusable, stateful logic.
  • Each call creates fresh state: composables share logic, not values.
  • Return a plain object of refs so callers can destructure and rename.
  • Accept refs (or computed values) as input when the value can change over time.
  • Put setup and cleanup (listeners, timers) inside the composable so callers cannot forget them.
  • Call composables synchronously at the top level of setup().
  • Use components to reuse markup and composables to reuse behavior.

Next, go deeper with ready-made patterns: Composable patterns.