Vue.js course · Module 9: Composables & VueUse

Composables in Production

8 min read ·
In this lesson5

The last stage before deploying NOVA LAB systems on Mars - let's learn proven patterns used in production Vue 3 applications. A prototype with three composables in one file works great as long as you work alone. In production there are dozens of composables, several people write them, and every type error only surfaces on the user's screen. So you need order in the files, types and flexible configuration.

Organizing Composable Files

In large projects a clear file structure is essential. Most often you will see a composables folder in which every composable has its own file named after the function:

src/
  composables/
    useAuth.ts         # Authorization
    useNotifications.ts # Notifications
    useSensors.ts      # Sensor data
    useTheme.ts        # App theme
    index.ts           # Re-export of all composables

The index.ts file is a so-called barrel file: it contains no logic, it only re-exports the functions from the other files, so a component can import everything from one place:

// composables/index.ts - central export point
export { useAuth } from './useAuth'
export { useNotifications } from './useNotifications'
export { useSensors } from './useSensors'
export { useTheme } from './useTheme'

// Import in component - clean and readable
import { useAuth, useNotifications } from '@/composables'

The @ alias points to the src folder - projects created with create-vue have it configured in Vite and in TypeScript. A barrel file has its price, though: the Vite performance guide recommends avoiding such files, because importing one function forces the dev server to fetch and transform all the re-exported modules. In a small folder it doesn't matter; in a large one it's better to import directly, for example from '@/composables/useAuth'.

Typing Composables with TypeScript

TypeScript provides type safety and better IDE hints. Vue exports the Ref<T> type for refs and ComputedRef<T> for computed values. We import them with the type keyword, because create-vue templates enable the verbatimModuleSyntax option, which requires type-only imports to be marked. The <T> parameter makes the composable generic, so it works with a list of any items:

import { ref, computed, type Ref, type ComputedRef } from 'vue'

// Interface for returned API
interface UsePaginationReturn<T> {
  currentPage: Ref<number>
  totalPages: ComputedRef<number>
  paginatedItems: ComputedRef<T[]>
  goToPage: (page: number) => void
  nextPage: () => void
  prevPage: () => void
}

// Typed composable
function usePagination<T>(
  items: Ref<T[]>,
  perPage: number = 10
): UsePaginationReturn<T> {
  const currentPage = ref(1)

  const totalPages = computed(() =>
    Math.ceil(items.value.length / perPage)
  )

  const paginatedItems = computed(() => {
    const start = (currentPage.value - 1) * perPage
    return items.value.slice(start, start + perPage)
  })

  function goToPage(page: number) {
    if (page >= 1 && page <= totalPages.value) {
      currentPage.value = page
    }
  }

  function nextPage() { goToPage(currentPage.value + 1) }
  function prevPage() { goToPage(currentPage.value - 1) }

  return {
    currentPage,
    totalPages,
    paginatedItems,
    goToPage,
    nextPage,
    prevPage
  }
}

When you pass a Ref<Experiment[]>, paginatedItems gets the type ComputedRef<Experiment[]> and the IDE suggests the experiment's fields. An explicit interface for the returned API is not mandatory, because TypeScript infers the type by itself, but it documents the composable's public contract.

Composable with Configuration Options

The options pattern allows flexible composable configuration - like the configuration panels of NOVA LAB modules. Instead of five parameters in a fixed order, the composable takes one object whose fields are all optional:

import { ref, onUnmounted } from 'vue'

interface UsePollingOptions {
  interval?: number
  immediate?: boolean
  retryOnError?: boolean
  maxRetries?: number
  onError?: (error: Error) => void
}

The question mark marks an optional field, and onError is a function the user can provide to find out about an error. We set the default values in the composable itself, while destructuring the options:

function usePolling<T>(
  fetchFn: () => Promise<T>,
  options: UsePollingOptions = {}
) {
  const {
    interval = 5000,
    immediate = true,
    retryOnError = true,
    maxRetries = 3,
    onError
  } = options

  const data = ref<T | null>(null)
  const error = ref<Error | null>(null)
  const isPolling = ref(false)
  const retryCount = ref(0)
  let timerId: ReturnType<typeof setInterval> | null = null

  async function poll() {
    try {
      data.value = await fetchFn()
      error.value = null
      retryCount.value = 0
    } catch (e) {
      // catch receives unknown - we turn it into an Error
      const err = e instanceof Error ? e : new Error(String(e))
      error.value = err
      onError?.(err)

      if (!retryOnError || retryCount.value >= maxRetries) {
        stopPolling()
        return
      }
      retryCount.value++
    }
  }

  function startPolling() {
    if (isPolling.value) return
    isPolling.value = true
    if (immediate) poll()
    timerId = setInterval(poll, interval)
  }

  function stopPolling() {
    isPolling.value = false
    if (timerId) {
      clearInterval(timerId)
      timerId = null
    }
  }

  onUnmounted(stopPolling)

  return { data, error, isPolling, retryCount, startPolling, stopPolling }
}

Three details set this code apart from a prototype. In strict mode the catch variable has the type unknown, so we turn it into an Error before passing it to onError. The ReturnType<typeof setInterval> type works both in the browser, where setInterval returns a number, and with Node.js types, where it returns an object. And onError?.(err) calls the function only if someone provided it. After an error, the next tick of the interval is a retry, up to maxRetries. This is how it looks with custom options:

// Usage with options
const sensorData = usePolling(
  () => fetch('/api/sensors').then(r => r.json()),
  {
    interval: 3000,
    immediate: true,
    maxRetries: 5,
    onError: (e) => console.error('Polling failed:', e)
  }
)

The omitted retryOnError takes its default value of true. The order of fields doesn't matter, and adding a new option in the future won't break existing calls.

Composable with provide/inject for Large Applications

In production applications we often need shared state without prop drilling, that is without passing props through several levels of components. So that inject knows the type of the provided value, Vue offers InjectionKey<T> - a symbol that carries type information. First we describe the data and the key:

import { ref, computed, provide, inject, readonly, type InjectionKey } from 'vue'

interface User {
  id: string
  name: string
}

interface AppNotification {
  id: number
  message: string
  type: string
  timestamp: Date
}

// We derive the store type from the function that creates it
type AppStore = ReturnType<typeof createAppStore>
const StoreKey: InjectionKey<AppStore> = Symbol('AppStore')

The name AppNotification instead of Notification is no accident - Notification is a built-in browser type. ReturnType makes sure the store type always matches what the function below really returns:

// Created once in the root component (App.vue)
function createAppStore() {
  const user = ref<User | null>(null)
  const isAuthenticated = computed(() => user.value !== null)
  const notifications = ref<AppNotification[]>([])

  function login(userData: User) { user.value = userData }
  function logout() { user.value = null }
  function notify(message: string, type = 'info') {
    notifications.value.push({
      id: Date.now(),
      message,
      type,
      timestamp: new Date()
    })
  }

  const store = {
    user: readonly(user),
    isAuthenticated,
    notifications: readonly(notifications),
    login,
    logout,
    notify
  }

  provide(StoreKey, store)
  return store
}

Components receive user and notifications as read-only, so only the store's methods change the state. What remains is the function for consumers:

// Used in any nested component
function useAppStore() {
  const store = inject(StoreKey)
  if (!store) {
    throw new Error('useAppStore requires createAppStore in App.vue')
  }
  return store
}

Thanks to InjectionKey, the result of useAppStore() is fully typed and the IDE suggests login, notify or user. Without a typed key, inject would return unknown.

Module Summary

In this module you learned advanced techniques for working with composables:

  • Factory composables - creating multiple composable instances with different configurations
  • Composition - combining composables into larger systems, a composable using another composable
  • Dependency Injection - provide/inject for shared state without prop drilling
  • Reactive patterns - Singleton, Event Bus, State Machine, Observer - all with Vue reactivity
  • VueUse - 200+ ready-made composables (useLocalStorage, useDark, useWindowSize)
  • Testing - unit testing composables with Vitest, mocking, nextTick for watchers, testing async operations
  • Optimization - shallowRef for large data, computed caching, avoiding memory leaks and cancelling requests
  • Production - TypeScript typing, file organization, configuration options pattern

These techniques will let you build scalable and efficient Vue 3 applications - ready for space missions!

My advice: when a composable has more than two configuration parameters, switch to an options object with default values, and describe the public API with types from the first version. You will deepen typing in Vue at the Quantum Laboratory, and Pinia will take over global state in the Mission Database. In the editor below, the app store works through provide/inject, and the sensor polling uses configuration options.

Remember: a production-ready composable is a station module with a user manual - it has its place in the warehouse, labeled connectors and sensible factory settings.

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

// ===== PRODUCTION COMPOSABLES DEMO =====

// 1. TypeScript-style typed composable with options
const StoreKey = Symbol('AppStore')

function createAppStore() {
  const user = ref({ name: 'Dr. Nova', role: 'commander' })
  const isAuthenticated = computed(() => user.value !== null)
  const notifications = ref([])

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

  function logout() { user.value = null }

  const store = { user: readonly(user), isAuthenticated, notifications: readonly(notifications), notify, logout }
  provide(StoreKey, store)
  return store
}

function useAppStore() {
  const store = inject(StoreKey)
  if (!store) throw new Error('Store not provided')
  return store
}

// 2. Polling composable with options pattern
function usePolling(fetchFn, options = {}) {
  const { interval = 3000, immediate = true, maxRetries = 3, onError } = options
  const data = ref(null)
  const error = ref(null)
  const isPolling = ref(false)
  const retryCount = ref(0)
  const pollCount = ref(0)
  let timerId = null

  async function poll() {
    try {
      data.value = await fetchFn()
      error.value = null
      retryCount.value = 0
      pollCount.value++
    } catch (e) {
      error.value = e.message || 'Error'
      onError?.(e)
      if (retryCount.value >= maxRetries) { stopPolling(); return }
      retryCount.value++
    }
  }

  function startPolling() {
    if (isPolling.value) return
    isPolling.value = true
    if (immediate) poll()
    timerId = setInterval(poll, interval)
  }

  function stopPolling() {
    isPolling.value = false
    if (timerId) { clearInterval(timerId); timerId = null }
  }

  onUnmounted(stopPolling)
  return { data, error, isPolling, retryCount, pollCount, startPolling, stopPolling }
}

// === Setup ===
const store = createAppStore()

// Simulate sensor API
const sensorPolling = usePolling(
  async () => {
    await new Promise(r => setTimeout(r, 500))
    if (Math.random() < 0.15) throw new Error('Sensor timeout')
    return {
      temperature: Math.round(-60 + Math.random() * 80),
      pressure: Math.round(90 + Math.random() * 30),
      oxygen: Math.round(85 + Math.random() * 15),
      timestamp: new Date().toLocaleTimeString()
    }
  },
  {
    interval: 2000,
    immediate: true,
    maxRetries: 5,
    onError: (e) => store.notify('Sensor error: ' + e.message, 'danger')
  }
)
</script>

<template>
  <div class="prod-lab">
    <h1>Composables in Production - NOVA LAB</h1>

    <section>
      <h2>App Store (provide/inject)</h2>
      <div v-if="store.isAuthenticated.value" class="user-info">
        <p>User: {{ store.user.value.name }} ({{ store.user.value.role }})</p>
        <button @click="store.logout()">Logout</button>
      </div>
      <p v-else class="warn">Not authenticated</p>
      <button @click="store.notify('System check OK', 'info')">Add Info</button>
      <button @click="store.notify('Low battery', 'warning')">Add Warning</button>
      <div class="notifs">
        <div v-for="n in store.notifications.value" :key="n.id" class="notif" :class="n.type">
          <span class="time">{{ n.timestamp }}</span> {{ n.message }}
        </div>
      </div>
    </section>

    <section>
      <h2>Polling with Options</h2>
      <div class="poll-controls">
        <button @click="sensorPolling.startPolling()" :disabled="sensorPolling.isPolling.value" class="start">Start</button>
        <button @click="sensorPolling.stopPolling()" :disabled="!sensorPolling.isPolling.value" class="stop">Stop</button>
      </div>
      <p class="poll-info">
        Polling: {{ sensorPolling.isPolling.value ? 'ACTIVE' : 'STOPPED' }} |
        Polls: {{ sensorPolling.pollCount.value }} |
        Retries: {{ sensorPolling.retryCount.value }}
      </p>
      <div v-if="sensorPolling.data.value" class="sensor-data">
        <div class="sensor">Temp: {{ sensorPolling.data.value.temperature }}°C</div>
        <div class="sensor">Pressure: {{ sensorPolling.data.value.pressure }} kPa</div>
        <div class="sensor">O2: {{ sensorPolling.data.value.oxygen }}%</div>
        <div class="sensor time">{{ sensorPolling.data.value.timestamp }}</div>
      </div>
      <div v-if="sensorPolling.error.value" class="error">{{ sensorPolling.error.value }}</div>
    </section>
  </div>
</template>

<style scoped>
.prod-lab { background: #0a0e27; color: #e0e0ff; padding: 1.5rem; min-height: 100vh; font-family: 'Courier New', monospace; }
h1 { color: #00ff88; text-align: center; }
h2 { color: #00b4d8; border-bottom: 1px solid #00b4d8; padding-bottom: 0.5rem; }
section { margin: 1.5rem 0; }
button { background: #00b4d8; color: #fff; border: none; padding: 0.4rem 0.8rem; border-radius: 4px; cursor: pointer; margin: 0.2rem; font-family: inherit; }
button:hover { background: #00ff88; color: #0a0e27; }
button:disabled { opacity: 0.4; }
button.start { background: #00ff88; color: #0a0e27; }
button.stop { background: #ff0055; }
.user-info { background: rgba(0,255,136,0.1); border: 1px solid #00ff88; border-radius: 6px; padding: 0.8rem; margin: 0.5rem 0; }
.warn { color: #ffb400; }
.notifs { margin-top: 0.5rem; max-height: 200px; overflow-y: auto; }
.notif { font-size: 0.8rem; padding: 0.3rem 0.6rem; margin: 0.2rem 0; border-radius: 3px; }
.notif.info { background: rgba(0,180,216,0.1); border-left: 3px solid #00b4d8; }
.notif.warning { background: rgba(255,180,0,0.1); border-left: 3px solid #ffb400; }
.notif.danger { background: rgba(255,0,85,0.1); border-left: 3px solid #ff0055; }
.time { color: #888; margin-right: 0.5rem; font-size: 0.75rem; }
.poll-controls { display: flex; gap: 0.5rem; margin: 0.5rem 0; }
.poll-info { color: #00b4d8; font-size: 0.9rem; }
.sensor-data { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 0.5rem; margin: 0.5rem 0; }
.sensor { background: rgba(0,180,216,0.1); border: 1px solid #00b4d8; border-radius: 6px; padding: 0.6rem; text-align: center; font-weight: bold; }
.sensor.time { color: #888; font-weight: normal; font-size: 0.8rem; }
.error { background: rgba(255,0,85,0.1); border: 1px solid #ff0055; color: #ff0055; padding: 0.5rem; border-radius: 4px; margin: 0.5rem 0; }
</style>

Docs entries used in this lesson

Spotted a mistake in this lesson?

  1. Project to submitLab Manager System - Mentor
  2. VideoModule Summary

Useful articles