The Composition API solved a real problem with the Options API: logic belonging to a single feature (pagination, filtering, a WebSocket subscription) is no longer scattered across data, computed, methods and watch. But that freedom has a downside: without discipline, composables become a new way to create hidden coupling, accidentally shared state, or memory leaks through listeners that never get cleaned up. This post covers how to structure composables that stay predictable at scale.
The problem: state unintentionally shared across instances
The most common mistake with a first composable is creating the reactive state outside the composable function, at module level.
// useCounter.js - BUG: state is shared across every component calling useCounter()
import { ref } from 'vue';
const count = ref(0); // created exactly once, when the module loads
export function useCounter() {
function increment() {
count.value++;
}
return { count, increment };
}
Two independent components calling useCounter() end up sharing the same count, because ref(0) only runs once, on module import. Incrementing the counter in one component moves the display in the other, with neither component having any reason to suspect it.
Why it happens: confusing a module singleton with per-instance state
It's the exact same mechanism that makes composables powerful for intentional global state (an auth store shared across the whole app) and dangerous for state you assume is local to each component. The line between the two isn't visible in the syntax: useCounter() and useAuth() are called the same way, but one needs to create fresh state on every call, the other needs to reuse the same one.
Diagnosing it: check where the ref lives
The diagnostic rule is easy to check in code: if the ref or reactive is declared inside the composable function, each call creates an independent instance. If it's declared outside, at module level, it's shared by every caller.
// useCounter.js - fixed: state lives inside the composable function
import { ref } from 'vue';
export function useCounter(initialValue = 0) {
const count = ref(initialValue); // created on every call to useCounter()
function increment() {
count.value++;
}
return { count, increment };
}
For genuinely global, intentional state, the reverse pattern - module-level state - is the right one, but it should be explicit and documented as such, ideally keeping the composable conceptually singular ("there is only one useAuthStore").
The fix: composables with explicit lifecycle and cleanup
Clean up side effects systematically
A composable that subscribes to an event, a WebSocket, or a setInterval must clean up that subscription in onUnmounted, otherwise every mount/unmount cycle of the component accumulates ghost listeners that keep running in the background.
// useWindowSize.js
import { ref, onMounted, onUnmounted } from 'vue';
export function useWindowSize() {
const width = ref(window.innerWidth);
const height = ref(window.innerHeight);
function handleResize() {
width.value = window.innerWidth;
height.value = window.innerHeight;
}
onMounted(() => window.addEventListener('resize', handleResize));
onUnmounted(() => window.removeEventListener('resize', handleResize));
return { width, height };
}
The classic trap with this pattern: calling a composable conditionally (inside an if, after an asynchronous mount) breaks lifecycle hooks, because Vue associates onMounted/onUnmounted with the active component instance at the time of the call. Composables must be called at the top of setup() or <script setup>, never inside a conditional branch or after an await.
<script setup>
// WRONG: after an await, the active component instance has been lost
async function setup() {
await someAsyncCheck();
const { width } = useWindowSize(); // onMounted won't attach to anything
}
</script>
Expose a consistent API with readonly where it matters
A composable that exposes internal state as read-write without explicit intent invites consuming components to mutate it directly, recreating the same fuzzy traceability as mutable global variables.
// usePagination.js
import { ref, computed, readonly } from 'vue';
export function usePagination(totalItems, pageSize = 20) {
const currentPage = ref(1);
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize));
function goToPage(page) {
if (page < 1 || page > totalPages.value) return;
currentPage.value = page;
}
return {
currentPage: readonly(currentPage), // read-only for consumers
totalPages,
goToPage, // the only sanctioned way to change currentPage
};
}
readonly forces consumers to go through goToPage, which centralizes validation (an out-of-range page, for instance) in a single place instead of duplicating it in every component that touches currentPage directly.
Composing several composables without hidden dependencies
A composable calling another composable works fine as long as the dependency is explicit in the parameters. The trap is making a composable depend on globally injected state implicitly (via inject() with no clear default), which makes unit testing impossible without reconstructing the entire provider tree.
// useCart.js - explicit dependency rather than implicit injection
import { ref, computed } from 'vue';
export function useCart(pricingService) {
const items = ref([]);
const total = computed(() =>
items.value.reduce((sum, item) => sum + pricingService.getPrice(item), 0)
);
function addItem(item) {
items.value.push(item);
}
return { items, total, addItem };
}
// useCart.test.js - pricingService is a plain mock, no Vue provider to mount
import { useCart } from './useCart';
test('computes the total using the provided pricing service', () => {
const mockPricingService = { getPrice: (item) => item.price * item.qty };
const { items, total, addItem } = useCart(mockPricingService);
addItem({ price: 10, qty: 2 });
expect(total.value).toBe(20);
});
Avoiding reactivity loss on destructuring
A subtler bug than shared module state shows up when a composable returns a reactive object instead of individual refs, and the consumer destructures it. Destructuring a plain reactive object in JavaScript copies the current primitive values out, breaking the reactive connection entirely.
// useMousePosition.js - returns a single reactive object
import { reactive, onMounted, onUnmounted } from 'vue';
export function useMousePosition() {
const position = reactive({ x: 0, y: 0 });
function update(event) {
position.x = event.clientX;
position.y = event.clientY;
}
onMounted(() => window.addEventListener('mousemove', update));
onUnmounted(() => window.removeEventListener('mousemove', update));
return position;
}
<script setup>
import { useMousePosition } from './useMousePosition';
// BUG: destructuring a reactive object snapshots x and y as plain numbers;
// the template below never updates after the initial render
const { x, y } = useMousePosition();
</script>
Two fixes address this, each with a different intent. toRefs converts every property of a reactive object into an individual ref that stays linked to the source, which is the right call when the composable's author wants destructuring to be safe for consumers:
// useMousePosition.js - exposes toRefs so destructuring stays reactive
import { reactive, toRefs, onMounted, onUnmounted } from 'vue';
export function useMousePosition() {
const position = reactive({ x: 0, y: 0 });
function update(event) {
position.x = event.clientX;
position.y = event.clientY;
}
onMounted(() => window.addEventListener('mousemove', update));
onUnmounted(() => window.removeEventListener('mousemove', update));
return toRefs(position);
}
<script setup>
import { useMousePosition } from './useMousePosition';
// Safe now: x and y are individual refs, each tracked independently
const { x, y } = useMousePosition();
</script>
The alternative, simpler fix is to design the composable's public contract around individual refs from the start rather than a single reactive object, which sidesteps the question entirely. As a rule of thumb: a composable meant to be destructured by consumers should either return plain refs or explicitly apply toRefs before returning; a composable meant to be used as a single cohesive object (passed down as one prop, for instance) can keep reactive without conversion.
The tradeoffs
Forcing explicit dependency injection into every composable can make the signature verbose for simple cases, and may feel excessive for a trivial composable with no external dependency. The pragmatic rule: explicit by default as soon as there's a testable dependency (an HTTP service, a pricing service, a clock for time-based tests), inject() acceptable for truly cross-cutting configuration (theme, locale) that never changes the behavior being unit-tested.
readonly has a marginal performance cost (it wraps the value in an additional proxy) that's negligible in the vast majority of cases, but can become measurable on very large data structures updated at high frequency (a real-time feed with thousands of updates per second).
When a composable isn't enough anymore
For state shared between components with no direct parent-child relationship, and that needs to persist beyond an individual component's lifecycle (a shopping cart, a user session), a composable with module-level state works for simple needs, but a dedicated state management library (Pinia) becomes preferable once the logic includes persistence, undo/redo, or debugging tooling (Vue Devtools natively displays Pinia stores, not arbitrary state hidden inside a module).
The point to keep: a Vue 3 composable is only predictable if you can tell, just by reading it, whether its state is recreated on every call or shared globally, and whether its side effects are cleaned up deterministically. Those two guarantees, not the Composition API syntax itself, are what separates reusable logic from a source of hard-to-trace bugs.
