The cart logic (count, total and the add function) is written in the MenuPage component. The cart icon in the header needs exactly the same logic. Copy it? Then every new rule, such as a discount, means changing two places together. How do you share logic without copying code?
The answer is a composable: a plain function whose name starts with use. It holds reactive data and the functions that change it. With a composable, the same logic can be used in many components. Picture the recipe card "how to take an order" that Mrs. Sri pins up in the kitchen. Every new cashier follows the same card, and each writes in their own order book. In Vue, the recipe card is the composable, and every cashier following it is a component that calls the composable. The order book is each caller's state. State is the reactive data that is kept, such as count and total.
A composable: the cart logic in one function
Here is the composable useCart, in its own file:
// src/composables/useCart.js
import { ref } from "vue"
export function useCart() {
const count = ref(0)
const total = ref(0)
function add(price) {
count.value++
total.value += price
}
return { count, total, add }
}
MenuPage calls it, then uses the result in its template:
<!-- MenuPage.vue -->
<script setup>
import { useCart } from "@/composables/useCart"
const { count, total, add } = useCart()
</script>
<template>
<button @click="add(15)">Add Fried Rice</button>
<p>Cart: {{ count }} item, ${{ total }}</p>
</template>
| Click | count |
total |
Screen |
|---|---|---|---|
| start | 0 | 0 | Cart: 0 item, $0 |
| Add Fried Rice | 1 | 15 | Cart: 1 item, $15 |
| Add Fried Rice | 2 | 30 | Cart: 2 item, $30 |
- Its name starts with
use:useCart,useCounter,useToggle. That's a shared habit (a convention), not a JavaScript rule, but every Vue developer reads it as "this is a composable". - Inside it you may use every function of the Composition API:
ref,reactive,computed,watch,onMounted. - A composable returns its refs (
count, notcount.value) and the functions that change them. Each ref is a box, so taking the result apart (destructuring) withconst { count, total, add } = ...gives the component the same box, not a copy of what it holds. Socountin the component stays reactive. - A composable is called in
<script setup>(or in another composable), right while the component is being created. The watchers and lifecycle hooks inside it then attach to the component that called it. - In a real project, a composable lives in its own file, usually in the
src/composables/folder, and isexported.
In the exercise editor
The editor has no other files, so the composable is written as a function in the script part, with no export and no import:
function useCounter(initial = 0) {
const count = ref(initial)
const increment = () => count.value++
const reset = () => count.value = initial
return { count, increment, reset }
}
const { count, increment, reset } = useCounter(0)
---template---
<div>
<span id="count">{{ count }}</span>
<button id="inc" @click="increment">+1</button>
<button id="reset" @click="reset">Reset</button>
</div>
initial = 0is the parameter's default value:useCounter()starts at 0,useCounter(5)starts at 5.- The number shown: it starts at
0, a +1 click makes1, another click makes2, and Reset goes back to0.incrementmust add (count.value++), not set 1. - The second exercise has the same shape:
useToggle(initial = false)keepsisOn = ref(initial), andtoggleflips it withisOn.value = !isOn.value. The composable is used asuseToggle(true). The template is{{ isOn ? "ON" : "OFF" }}:ONat the start,OFFafter one click,ONagain after two. - The arrow function form works too:
const useToggle = (initial = false) => { ... }.
Return the ref, not its contents
Here are four ways to return data from a composable. Two are right, two are wrong:
return { count, total, add } // right: refs
return { ...toRefs(cart), add } // right: toRefs of a reactive object
return { ...cart, add } // wrong: copied numbers
return data.value // wrong: only what it holds right now
| What is returned | After destructuring | One click on Add |
|---|---|---|
{ count, total, add } |
refs | screen 1 item, $15 |
{ ...toRefs(cart), add } |
refs linked to cart |
screen 1 item, $15 |
{ ...cart, add } |
plain number 0 | screen stays 0 item, $0 |
{ ...cart } (the three dots copy every property of an object) copies what the reactive object holds at that moment. So all the component gets is the number 0. add still changes cart inside the composable, but the screen doesn't change. The same happens with return data.value, for example when data is a ref that is filled later from a server. When the composable is called, data is still null, so null is what gets returned, and data that arrives later never reaches the screen. Return data (the ref) or { data }.
Every call has its own state
For example, CartIcon in the header and MenuPage both call useCart(). The Add Fried Rice button in MenuPage is clicked twice, and its text becomes "2 item, $30". Take a guess: does the icon in the header show Cart (2) or Cart (0)?
The icon in the header still says Cart (0). count and total are created inside useCart, so every call makes new refs. CartIcon and MenuPage each have their own cart.
If all components must share one cart, create its refs outside the function:
const count = ref(0) // created once, when the file loads
const total = ref(0)
export function useCart() {
function add(price) {
count.value++
total.value += price
}
return { count, total, add }
}
Now every caller holds the same refs, and the icon in the header becomes Cart (2) too. For state shared across the whole app, the standard tool is Pinia, covered in the Pinia lesson later.
📌 Composables and mixins
Vue 2 shared logic through mixins: objects with data and methods (parts of a Vue 2 style component) merged silently into a component. Mixins have two problems. The template doesn't show which mixin count came from. And two mixins that both have count overwrite each other. Composables solve both problems. Where count comes from is visible in the line const { count } = useCart(). A clashing name can be renamed while taking the result apart, such as const { count: tableCount } = useCart(). A composable can also take parameters, like useCounter(5).
Parameters that can change. useCounter(5) takes a plain number, so its value is read once. The parameter can also be a ref or a getter (a function that returns a value), for example the id of the menu item picked right now. Read a parameter like that with toValue() inside watchEffect (the Watchers lesson), so the result changes with it. In this example, menuList is an array of the stall's dishes, each with an id:
import { ref, watchEffect, toValue } from "vue"
function useMenu(id) {
const menu = ref(null)
watchEffect(() => {
menu.value = menuList.find((m) => m.id === toValue(id))
})
return { menu }
}
const pickedId = ref(1)
const { menu } = useMenu(pickedId) // or useMenu(() => props.id), or useMenu(2)
toValue()(Vue 3.3 and later) takes three forms. From a ref,toValue()takes what it holds. From a getter,toValue()calls the getter and takes its result. A plain value is returned as it is.- We tried it on Vue 3.5.45:
pickedIdchanged from 1 to 2, andmenuchanged from Fried Rice to Chicken Noodles. IftoValue(id)is read outsidewatchEffect,menustays Fried Rice. - The library VueUse (
@vueuse/core) has many ready-made composables written with this pattern.
⚠️ What makes a composable go quiet, or fail the exercise
- Returning
.value.return data.valuecuts reactivity. Return the ref. - Destructuring a
reactiveobject.return { ...cart }sends a copy. UsetoRefs(cart), or usereffrom the start. - Calling a composable in an event handler or
setTimeout. No component is being created there. TheonMountedinside that composable never runs, and in development mode the console writes[Vue warn]: onMounted is called when there is no active component instance to be associated with.Call the composable in<script setup>. - A function name different from the brief. The exercise checks for
function useCounteroruseCounter =(anduseTogglein the second one), and that the component calls it (= useCounter(). Then the checker reloads the page and presses the button twice: the result must be2, andONagain for the toggle.
TL;DR: A composable is a useX function that wraps reactive data (state) and the functions that change it, so the same logic can be used in many components. For example, useCart() returns { count, total, add }. Return refs, not .value, so const { count } = useCart() (taking the result apart into separate variables) stays reactive. A reactive object is returned through toRefs. Call a composable in <script setup>. State created inside the function is new for every caller. State created outside the function is shared by all callers. In the exercise editor, a composable is written as a plain function in the script part, with no export and no import.
⚡ The cart logic in one function
Write:
// src/composables/useCart.js
import { ref } from "vue"
export function useCart() {
const count = ref(0)
const total = ref(0)
function add(price) {
count.value++
total.value += price
}
return { count, total, add }
}
Meaning: A composable is a plain function whose name starts with use, holding reactive data and the functions that change it. With a composable, the same logic can be used in many components. A component only needs to call it in <script setup>: const { count, total, add } = useCart().
⚡ Return the ref, not its contents
Guess first: a composable makes const data = ref(null), then does return data.value. Does data that arrives later, for example from a server, reach the screen?
No. data.value is only what the ref holds at that moment, null, so reactivity is lost.
Meaning: Return data (the ref) or { data }. Each ref is a box, so taking the result apart gives the component the same box, and its contents stay reactive.
⚡ Every call has its own state
Guess first: CartIcon and MenuPage both call useCart(). The Add button in MenuPage, which calls add, is clicked twice. Does the icon show Cart (2) or Cart (0)?
Cart (0). count and total are created inside the function, so every call makes new refs.
Meaning: State (reactive data such as count) created inside a composable is new for every caller. If all components must share one cart, create its refs outside the function. For state shared across the whole app, the standard tool is Pinia.