Composables
Extracting stateful logic into use-prefixed functions built on refs, watchers, and lifecycle hooks, and the conventions that make them reusable.
Watchers with watch and watchEffectLifecycle hooksProvide and inject
Composables
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A composable is an ordinary function, named with a use prefix by convention, that calls Composition API functions such as ref, computed, watch, or onMounted to package stateful logic for reuse.
- A function that only transforms its inputs and touches no reactivity or lifecycle API is a plain utility, not a composable, and it can live anywhere and be called at any time.
- Composables must be called synchronously during setup, because that is the moment Vue knows which component instance owns the watchers and lifecycle hooks they register, and it is what lets Vue clean them up on unmount.
- Each call to a composable creates fresh state for the calling component; state is only shared if it is created outside the function, at module level.
- Returning a plain object of refs lets callers destructure the result without losing reactivity, which is the convention the Vue docs and VueUse follow.
- Accepting MaybeRefOrGetter arguments and reading them with toValue inside a watcher lets one composable work with a static value, a ref, or a getter.
The problem: logic that is stuck inside one component
By now you can build a component that tracks the mouse position. It needs two refs, an event listener added on mount, and the same listener removed on unmount:
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
const x = ref(0)
const y = ref(0)
function update(event) {
x.value = event.pageX
y.value = event.pageY
}
onMounted(() => window.addEventListener('mousemove', update))
onUnmounted(() => window.removeEventListener('mousemove', update))
</script>
<template>Pointer at {{ x }}, {{ y }}</template>
Now a second component needs the same thing. Copying those twelve lines works once. By the fifth copy, a bug fix (say, switching to pointermove so touch devices work) has to be made five times, and someone will miss one.
In the Options API era, Vue’s answer was the mixin: an object of data, methods, and hooks that got merged into a component. Mixins had three real problems. You couldn’t tell from reading a component which mixin a property came from. Two mixins that both defined x collided silently. And mixins could only talk to each other through shared property names, an invisible contract. The Composition API was designed partly to fix this, and the fix is almost anticlimactic: put the code in a function.
A composable is a function that uses the Composition API
Move the state and the hooks into a function and return what callers need:
// composables/useMouse.js
import { ref, onMounted, onUnmounted } from 'vue'
export function useMouse() {
const x = ref(0)
const y = ref(0)
function update(event) {
x.value = event.pageX
y.value = event.pageY
}
onMounted(() => window.addEventListener('mousemove', update))
onUnmounted(() => window.removeEventListener('mousemove', update))
return { x, y }
}
<script setup>
import { useMouse } from './composables/useMouse'
const { x, y } = useMouse()
</script>
<template>Pointer at {{ x }}, {{ y }}</template>
That is the whole mechanism. There’s no registration step and no special API for declaring a composable. ref, onMounted, and watch don’t care whether they are called directly in <script setup> or three function calls deep. What they care about is when they are called, which is the next section.
Where every property comes from is now explicit: x and y come from useMouse(), right there in the import. If two composables both return x, you rename one while destructuring (const { x: mouseX } = useMouse()). The mixin problems are gone because this is plain JavaScript scoping (see closures if the way update keeps access to x and y is unfamiliar).
What makes a function a composable, and what doesn’t
Not every helper in a composables/ folder is one. The test the video works through is simple: does the function use Vue’s reactivity or lifecycle APIs to hold state over time?
// Not a composable: pure transformation, no Vue APIs.
export function formatPrice(cents, currency = 'USD') {
return new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(cents / 100)
}
// A composable: owns reactive state and a watcher.
export function useDebouncedRef(source, delay = 300) {
const debounced = ref(source.value)
let timer
watch(source, (value) => {
clearTimeout(timer)
timer = setTimeout(() => (debounced.value = value), delay)
})
onScopeDispose(() => clearTimeout(timer))
return debounced
}
The distinction matters because the two have different rules. formatPrice can be called anywhere: in a template, in an event handler, in a Node script. useDebouncedRef carries constraints, and naming it with use warns the reader.
The one rule: call composables during setup
Watchers and lifecycle hooks attach to the component instance that is currently running setup. Vue tracks that instance in an internal variable that is only set while setup() (or <script setup>) executes synchronously. That’s why this works:
<script setup>
const { x, y } = useMouse() // runs during setup: hooks attach to this component
</script>
And this doesn’t:
function onButtonClick() {
const { x } = useMouse() // no active instance: onMounted warns, listener never added
}
The payoff of this rule is automatic cleanup. Any watch, watchEffect, or computed created during setup is collected into the component’s effect scope and stopped when the component unmounts. Hooks like onUnmounted and onScopeDispose let a composable clean up the things Vue can’t see, like DOM listeners and timers. onScopeDispose is the more general of the two: it also runs when a manually created effectScope() is stopped, which makes it the better choice for composables that might be used outside a component.
One exception to know: inside <script setup>, the compiler restores the active instance after a top-level await, so calling a composable after await works there. In a hand-written setup() function it doesn’t.
This is also why composables can call inject(). Injection reads from the current instance’s ancestor chain, so a composable can pull something provided higher up (see provide and inject) without the component passing it in.
Conventions that make composables pleasant to use
Return an object of refs
Return a plain object whose properties are refs, not a reactive() object. Destructuring a reactive object copies out dead values; destructuring an object of refs keeps the refs:
const { x, y } = useMouse() // x and y are refs: stay live
const mouse = reactive(useMouse()) // caller opts into mouse.x unwrapping
Accept refs, getters, or plain values
A composable that takes an argument is more useful if the argument can change. Vue 3.3 added the MaybeRefOrGetter type and the toValue() helper for exactly this:
import { toValue, watchEffect, type MaybeRefOrGetter } from 'vue'
export function useTitle(title: MaybeRefOrGetter<string>) {
watchEffect(() => {
document.title = toValue(title)
})
}
useTitle('Settings') // static string
useTitle(pageTitle) // a ref
useTitle(() => `${unread.value} unread`) // a getter
toValue unwraps a ref, calls a getter, or passes a plain value through. Because it runs inside watchEffect, whatever reactive state it reads gets tracked. Calling toValue(title) once at the top of the composable, outside any effect, would read the value a single time and never update.
Keep side effects client-safe
If the app is server-rendered, setup runs on the server too, where there is no window. Put DOM access in onMounted, as useMouse does, since mount hooks only run in the browser. The SSR and hydration lesson goes further.
State is per call unless you hoist it
Each call to useMouse() runs the function body again, creating new refs and a new listener. Two components calling it don’t share state. Move the refs outside the function, to module scope, and every caller reads the same refs:
const count = ref(0) // module scope: one instance for the whole app
export function useSharedCounter() {
return { count, increment: () => count.value++ }
}
That is a legitimate way to share state, and also the start of a store. When that pattern starts to strain, when you need a store picks up the thread.
Composables vs. React hooks and renderless components
If you know React, composables will look like custom hooks, and the idea is the same: extract stateful logic into a use function. The execution model differs. A React component function re-runs on every render, so hooks must be called in the same order every time, and effects need dependency arrays. A Vue setup runs once per component instance. A composable’s refs are created once, its watchers track dependencies automatically, and there are no stale closures to manage. You can call a composable inside an if in setup without breaking anything, as long as it’s still during setup.
The other older pattern for sharing logic was the renderless component, which used a scoped slot to hand state down to its children (React’s equivalent is render props). It still works, but it adds a component instance purely to carry logic. A composable does the same job with no extra node in the tree. Renderless components still earn their place when the reusable thing is genuinely about rendering.
What the video covers
Alexander Lichter’s video is about the boundary this lesson spends its middle section on: when a function is really a composable and when it’s a plain function in a use costume. He gives a checklist and walks through four examples in <script setup>. It doesn’t go into the history behind composables (mixins), the toValue input convention, or module-level shared state, so the lesson covers those. The two talks under Go deeper pick up from there: Michael Thiessen on design patterns for larger composables, and Anthony Fu, the author of VueUse, on the conventions that library is built around.
Where this fits
You can now write your own. Before writing many more, look at the library of a few hundred already written and tested: VueUse.
Check yourself
Why must a composable that calls onMounted or watch be called synchronously inside <script setup> or setup(), and not from inside a setTimeout callback?
Lifecycle hooks and watchers attach themselves to the component instance that is currently running setup. Vue only knows that instance during the synchronous execution of setup. From a later callback there is no active instance, so onMounted has nothing to register with and a watcher created there is not stopped automatically when the component unmounts, which leaks it.
Two components both call useMouse(). One moves the pointer over a canvas. Do both components see the same x and y?
They see the same numbers only because both listen to the same window mousemove event, not because they share state. Each call created its own pair of refs and its own listener. If useMouse kept its refs in module scope instead of inside the function body, both components would read literally the same refs, and the composable would act like a tiny global store.
Why do composables usually return an object of refs instead of a reactive() object?
Destructuring a reactive object copies out plain values, so const { x } = reactive({ x: 0 }) gives a number that never updates. Destructuring an object whose properties are refs copies the refs themselves, which stay connected to the composable's state. A caller who prefers property access can still wrap the returned object in reactive() to unwrap the refs.
A useTitle(title) composable must work whether it is called with a string, a ref, or a getter like () => `${count.value} unread`. How do you write it?
Type the parameter as MaybeRefOrGetter<string> and read it with toValue inside a watchEffect, for example watchEffect(() => { document.title = toValue(title) }). toValue unwraps refs, calls getters, and returns plain values unchanged, and because the read happens inside the effect, any ref or reactive state the getter touches is tracked and the title updates when it changes.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.