Vue.js course · Module 9: Composables & VueUse

Advanced Composable Patterns

7 min read ·
In this lesson5

Welcome to the NOVA LAB Science Laboratory! You already know the basics of composables from the 3D Printing Workshop - now it's time for advanced design patterns. Let's start with a problem: the station tracks three resources, namely oxygen, fuel and water. Each needs the same logic - the current level, a percentage, an alarm when it runs low, consumption and refilling. Copying that logic into three components means three places to fix with every bug. Just as NOVA LAB engineers design modular space station systems, we will design composables ready for any challenge.

What you will learn

In the Science Laboratory you will master expert-level research protocols:

  • creating composable factories and combining composables into larger systems,
  • providing shared context with provide and inject, and handling errors with retries,
  • building reactive design patterns: singleton, event bus, state machine and observer,
  • using ready-made composables from the VueUse library,
  • testing composables in Vitest and optimizing their performance,
  • preparing composables for production: types, file organization and configuration options.

Factory Composables

A factory composable is a function that creates composables with different configurations - like a station module factory where each module has the same interfaces but different parameters. Its name starts with create rather than use to stress that every call produces a new, independent instance. Here is a factory that takes a resource name and a maximum capacity:

import { ref, computed } from 'vue'

// Factory: creates a composable for any resource
function createResourceManager(resourceName, maxCapacity = 100) {
  const currentLevel = ref(maxCapacity)
  const isLow = computed(() => currentLevel.value < maxCapacity * 0.2)
  const isCritical = computed(() => currentLevel.value < maxCapacity * 0.05)
  const percentage = computed(() =>
    Math.round((currentLevel.value / maxCapacity) * 100)
  )

  function consume(amount) {
    currentLevel.value = Math.max(0, currentLevel.value - amount)
  }

  function refill(amount) {
    currentLevel.value = Math.min(maxCapacity, currentLevel.value + amount)
  }

  return {
    resourceName,
    currentLevel,
    maxCapacity,
    percentage,
    isLow,
    isCritical,
    consume,
    refill
  }
}

The level starts at full capacity, isLow switches on below 20%, and isCritical below 5%. Math.max and Math.min keep the level from dropping below zero or exceeding the capacity. Now let's produce three managers:

// Usage - each resource has the same methods but independent state
const oxygen = createResourceManager('Oxygen', 500)
const fuel = createResourceManager('Fuel', 1000)
const water = createResourceManager('Water', 200)

oxygen.consume(50) // does not affect fuel or water

After this call oxygen has 450 units, which is 90%, while fuel is still a full 1000. Every call of the factory created its own refs, so the resources share nothing.

Composable Composition

Composables can use other composables - like connecting station modules into larger systems. First a base notification composable, which adds new entries to the beginning of the list and keeps at most the 50 most recent ones:

import { ref, computed, watch } from 'vue'

// Base composable
function useNotifications() {
  const notifications = ref([])

  function addNotification(message, type = 'info') {
    notifications.value.unshift({
      id: Date.now(),
      message,
      type,
      timestamp: new Date()
    })
    // Limit to 50 notifications
    if (notifications.value.length > 50) {
      notifications.value.pop()
    }
  }

  function clearAll() {
    notifications.value = []
  }

  return { notifications, addNotification, clearAll }
}

unshift inserts an element at the start of the array, and pop removes the last, oldest one. The lab monitor calls this composable inside itself and observes the sensors with watch, comparing the readings with the limits from the thresholds parameter:

// Composable that uses another composable
function useLabMonitor(thresholds) {
  const temperature = ref(22)
  const pressure = ref(101)
  const { notifications, addNotification, clearAll } = useNotifications()

  watch(temperature, (val) => {
    if (val > thresholds.maxTemp) {
      addNotification(
        `Critical temperature: ${val}°C!`,
        'danger'
      )
    }
  })

  watch(pressure, (val) => {
    if (val < thresholds.minPressure) {
      addNotification(
        `Pressure below normal: ${val} kPa`,
        'warning'
      )
    }
  })

  return {
    temperature,
    pressure,
    notifications,
    addNotification,
    clearAll
  }
}

The component sees one composable, even though two are working underneath. Every call of useLabMonitor also gets its own list of notifications - a second monitor starts with an empty list.

Dependency Injection in Composables

You know the provide and inject mechanism from the Communication Station. Wrapped in a pair of composables, it becomes a central station system available to every module below. The key is a Symbol, which guarantees that no other library overwrites our key:

import { ref, provide, inject } from 'vue'

// Symbol as key - avoids name collisions
const MissionContextKey = Symbol('MissionContext')

// Composable providing context
function provideMissionContext() {
  const missionName = ref('Mars Exploration 2087')
  const crewCount = ref(6)
  const missionDay = ref(1)

  const context = {
    missionName,
    crewCount,
    missionDay,
    advanceDay() { missionDay.value++ }
  }

  provide(MissionContextKey, context)
  return context
}

// Composable consuming context
function useMissionContext() {
  const context = inject(MissionContextKey)
  if (!context) {
    throw new Error(
      'useMissionContext requires provideMissionContext in a parent component'
    )
  }
  return context
}

If someone calls useMissionContext without a provider higher up in the tree, they immediately get a clear error instead of a mysterious undefined. You call both composables in <script setup>, because provide and inject only work while the component is being created:

<!-- ParentComponent.vue -->
<script setup>
const { missionName, missionDay, advanceDay } = provideMissionContext()
</script>

<!-- ChildComponent.vue (any nesting depth) -->
<script setup>
const { missionName, missionDay } = useMissionContext()
// Automatically reactive - changes in parent update children
</script>

The context contains refs, so when the parent calls advanceDay(), every child immediately sees the new mission day.

Error Handling in Composables

Every station system needs safeguards in case of failure. The composable below wraps any async function: it tracks the loading state, stores the error in a ref instead of losing it, and allows at most three retries:

import { ref, computed } from 'vue'

function useAsyncOperation(asyncFn) {
  const data = ref(null)
  const error = ref(null)
  const loading = ref(false)
  const retryCount = ref(0)
  const MAX_RETRIES = 3

  const hasError = computed(() => error.value !== null)
  const canRetry = computed(() => retryCount.value < MAX_RETRIES)

  async function execute(...args) {
    loading.value = true
    error.value = null

    try {
      data.value = await asyncFn(...args)
      retryCount.value = 0 // Reset on success
    } catch (e) {
      error.value = e.message || 'Unknown error'
      console.error(`Operation failed: ${error.value}`)
    } finally {
      loading.value = false
    }
  }

  async function retry(...args) {
    if (!canRetry.value) {
      error.value = 'Retry limit exceeded'
      return
    }
    retryCount.value++
    await execute(...args)
  }

  return { data, error, loading, hasError, canRetry, retryCount, execute, retry }
}

The try/catch/finally block guarantees that loading returns to false whatever the result. After three failed retries, retry stops calling the server and sets the retry limit message. This is how it is used with a temperature sensor:

// Usage
const sensorData = useAsyncOperation(async (sensorId) => {
  const response = await fetch(`/api/sensors/${sensorId}`)
  if (!response.ok) throw new Error('Failed to fetch data')
  return response.json()
})

// In a component
await sensorData.execute('temp-sensor-1')
if (sensorData.hasError.value && sensorData.canRetry.value) {
  await sensorData.retry('temp-sensor-1')
}

Watch out for the last lines: a top-level await in <script setup> turns the component into an async dependency that requires <Suspense> - you remember that from the Module Storage. In practice, call execute in onMounted or in a click handler.

My advice: return a plain object of refs from a composable, as in every example in this lesson. The component can then destructure it without losing reactivity. In the next lesson we will use these building blocks to create classic design patterns. In the editor below, the resource managers, the monitor with notifications and the operation with retries all work on one panel.

Remember: a composable is a station module with a standard connector - the factory produces as many as you need, and each has its own independent state.

Code for this lesson: App.vue
<script setup>
import { ref, computed, provide, inject, readonly } from 'vue'

// ===== FACTORY COMPOSABLE =====
// Creates a composable for any station resource
function createResourceManager(resourceName, maxCapacity = 100) {
  const currentLevel = ref(maxCapacity)
  const isLow = computed(() => currentLevel.value < maxCapacity * 0.2)
  const isCritical = computed(() => currentLevel.value < maxCapacity * 0.05)
  const percentage = computed(() =>
    Math.round((currentLevel.value / maxCapacity) * 100)
  )

  function consume(amount) {
    currentLevel.value = Math.max(0, currentLevel.value - amount)
  }

  function refill(amount) {
    currentLevel.value = Math.min(maxCapacity, currentLevel.value + amount)
  }

  return {
    resourceName,
    currentLevel,
    maxCapacity,
    percentage,
    isLow,
    isCritical,
    consume,
    refill
  }
}

// ===== COMPOSABLE COMPOSITION =====
// useNotifications is used inside useLabMonitor
function useNotifications() {
  const notifications = ref([])

  function addNotification(message, type = 'info') {
    notifications.value.unshift({
      id: Date.now(),
      message,
      type,
      timestamp: new Date().toLocaleTimeString()
    })
    if (notifications.value.length > 20) notifications.value.pop()
  }

  function clearAll() { notifications.value = [] }

  return { notifications, addNotification, clearAll }
}

// ===== ERROR HANDLING =====
function useAsyncOperation(asyncFn) {
  const data = ref(null)
  const error = ref(null)
  const loading = ref(false)
  const retryCount = ref(0)

  async function execute(...args) {
    loading.value = true
    error.value = null
    try {
      data.value = await asyncFn(...args)
    } catch (e) {
      error.value = e.message || 'Unknown error'
    } finally {
      loading.value = false
    }
  }

  async function retry(...args) {
    if (retryCount.value >= 3) {
      error.value = 'Max retries reached'
      return
    }
    retryCount.value++
    await execute(...args)
  }

  return { data, error, loading, retryCount, execute, retry }
}

// === Create Resources (Factory pattern) ===
const oxygen = createResourceManager('Oxygen', 500)
const fuel = createResourceManager('Fuel', 1000)
const water = createResourceManager('Water', 200)

// === Use Notifications (Composition) ===
const { notifications, addNotification, clearAll } = useNotifications()

// === Async Operation (Error Handling) ===
const sensorOp = useAsyncOperation(async (id) => {
  // Simulate API
  await new Promise(r => setTimeout(r, 800))
  if (Math.random() < 0.3) throw new Error('Connection lost')
  return { id, temp: Math.round(Math.random() * 50 - 20), status: 'OK' }
})

function consumeResource(resource, amount) {
  resource.consume(amount)
  if (resource.isCritical.value) {
    addNotification(resource.resourceName + ' CRITICAL!', 'danger')
  } else if (resource.isLow.value) {
    addNotification(resource.resourceName + ' low', 'warning')
  }
}
</script>

<template>
  <div class="lab">
    <h1>Advanced Composables - NOVA LAB</h1>

    <section class="resources">
      <h2>Factory Composables - Resources</h2>
      <div class="res-grid">
        <div v-for="res in [oxygen, fuel, water]" :key="res.resourceName" class="res-card"
          :class="{ low: res.isLow.value, critical: res.isCritical.value }">
          <h3>{{ res.resourceName }}</h3>
          <div class="bar"><div class="fill" :style="{ width: res.percentage.value + '%' }"></div></div>
          <p>{{ res.currentLevel.value }} / {{ res.maxCapacity }} ({{ res.percentage.value }}%)</p>
          <div class="btns">
            <button @click="consumeResource(res, 20)">Use 20</button>
            <button @click="consumeResource(res, 50)">Use 50</button>
            <button @click="res.refill(30)">Refill 30</button>
          </div>
        </div>
      </div>
    </section>

    <section class="async-section">
      <h2>Error Handling - Async Operation</h2>
      <button @click="sensorOp.execute('T-01')" :disabled="sensorOp.loading.value">
        {{ sensorOp.loading.value ? 'Loading...' : 'Fetch Sensor' }}
      </button>
      <button v-if="sensorOp.error.value" @click="sensorOp.retry('T-01')">
        Retry ({{ sensorOp.retryCount.value }}/3)
      </button>
      <div v-if="sensorOp.data.value" class="result ok">{{ JSON.stringify(sensorOp.data.value) }}</div>
      <div v-if="sensorOp.error.value" class="result err">Error: {{ sensorOp.error.value }}</div>
    </section>

    <section class="notif-section">
      <h2>Notifications (Composition)</h2>
      <button @click="clearAll" v-if="notifications.length">Clear All</button>
      <div v-for="n in notifications" :key="n.id" class="notif" :class="n.type">
        <span class="time">{{ n.timestamp }}</span> {{ n.message }}
      </div>
      <p v-if="!notifications.length" class="empty">No notifications</p>
    </section>
  </div>
</template>

<style scoped>
.lab { background: #0a0e27; color: #e0e0ff; padding: 1.5rem; min-height: 100vh; font-family: 'Courier New', monospace; }
h1 { color: #00ff88; text-align: center; margin-bottom: 2rem; }
h2 { color: #00b4d8; border-bottom: 1px solid #00b4d8; padding-bottom: 0.5rem; }
.res-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin: 1rem 0; }
.res-card { background: rgba(0,180,216,0.1); border: 2px solid #00b4d8; border-radius: 8px; padding: 1rem; }
.res-card.low { border-color: #ffb400; }
.res-card.critical { border-color: #ff0055; animation: pulse 1s infinite; }
.res-card h3 { color: #00ff88; margin: 0 0 0.5rem; }
.bar { background: #1a1e3f; border-radius: 4px; height: 16px; overflow: hidden; margin: 0.5rem 0; }
.fill { height: 100%; background: linear-gradient(90deg, #00ff88, #00b4d8); transition: width 0.3s; border-radius: 4px; }
.res-card.low .fill { background: linear-gradient(90deg, #ffb400, #ff8800); }
.res-card.critical .fill { background: #ff0055; }
.btns { display: flex; gap: 0.3rem; flex-wrap: wrap; margin-top: 0.5rem; }
button { background: #00b4d8; color: #fff; border: none; padding: 0.4rem 0.8rem; border-radius: 4px; cursor: pointer; font-family: inherit; }
button:hover { background: #00ff88; color: #0a0e27; }
button:disabled { opacity: 0.5; }
.async-section { margin: 1.5rem 0; }
.async-section button { margin-right: 0.5rem; }
.result { padding: 0.5rem; border-radius: 4px; margin-top: 0.5rem; font-size: 0.9rem; }
.result.ok { background: rgba(0,255,136,0.1); border: 1px solid #00ff88; }
.result.err { background: rgba(255,0,85,0.1); border: 1px solid #ff0055; color: #ff0055; }
.notif-section { margin: 1.5rem 0; }
.notif { padding: 0.4rem 0.8rem; margin: 0.3rem 0; border-radius: 4px; font-size: 0.85rem; }
.notif.info { background: rgba(0,180,216,0.15); border-left: 3px solid #00b4d8; }
.notif.warning { background: rgba(255,180,0,0.15); border-left: 3px solid #ffb400; }
.notif.danger { background: rgba(255,0,85,0.15); border-left: 3px solid #ff0055; }
.time { color: #888; margin-right: 0.5rem; }
.empty { color: #666; font-style: italic; }
@keyframes pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.6; } }
</style>

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is a factory composable?

  2. 2. What is the main advantage of composable composition (a composable using another composable)?

These are 2 of 4 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Build createResourceManager that accepts name and maxCapacity. Return currentLevel (ref), percentage (computed), consume() and refill().

  • Click in order

    Arrange the correct provide syntax with Symbol:

  • Code editor

    Build useAsyncOperation with execute(), retry(), refs: data, error, loading, retryCount and computed: hasError, canRetry.

  • Horizontal ordering

    Arrange the correct inject call with the context key:

  1. QuestionFactory Composables
  2. QuestionComposable Composition
  3. Coding taskPractice: Factory Composable
  4. QuestionDependency Injection in Composables
  5. Click in orderProvide Syntax in a Composable
  6. QuestionError Handling in Composables
  7. Coding taskPractice: Composable with Error Handling
  8. Put in orderCalling inject in a Composable

Useful articles