A composable is a function that encapsulates reactive state and logic for reuse—Vue’s equivalent of React custom hooks. Name composables useSomething by convention.
Example shape
function useCounter(initial = 0) {
const count = ref(initial);
function increment() { count.value += 1; }
return { count, increment };
}
Each call creates independent refs—call useCounter() twice for two unrelated counters, just like calling a custom hook twice in React.
What belongs in composables
- Shared form field logic, pagination, fetch + loading/error state
- DOM listeners with automatic cleanup via lifecycle hooks inside the composable
- Domain rules that multiple components need
Testing benefit
Composables are plain functions—test them without mounting components by checking returned refs and calling exposed methods.
Self-check
- Why prefix composables with
use? - Do two components sharing a composable share the same ref automatically?
Challenge
useToggle composable
- Extract
useToggle(initial)returningopenandtoggle. - Use it for two independent panels in
App.
Done when: each panel toggles independently using the same composable logic.
Challenge
Extract useCounter
- Move increment logic into
function useCounter(initial). - Use two counters in the same parent.
Done when: both counters work independently from shared composable logic.
Interview prep
- What is a composable?
A reusable
function useX()that encapsulates reactive state and logic—like custom hooks in React, shared across components.