Vue.js course · Module 9: Composables & VueUse

Reactive Design Patterns

7 min read ·
In this lesson4

In the NOVA LAB control center every system must be reliable and predictable. The problem appears when modules have to cooperate: the theme panel and the notification panel should see the same data, a sensor has to alert several systems at once, and an experiment must not jump from "aborted" straight to "completed". Design patterns with Vue 3 reactivity let you build such systems - like the proven engineering protocols of a space station.

Reactive Singleton

Sometimes we need a single shared instance of state - like the station's central computer that all modules use. The trick is where the state is created: we create the reactive object outside the composable function, at the JavaScript module level, so it exists exactly once. The readonly function returns a read-only version of it:

import { reactive, readonly } from 'vue'

// State created ONCE, outside the function
const globalState = reactive({
  currentUser: null,
  theme: 'dark',
  locale: 'pl',
  notifications: []
})

// Composable returns the same state every time
export function useGlobalStore() {
  function setUser(user) {
    globalState.currentUser = user
  }

  function setTheme(theme) {
    globalState.theme = theme
  }

  function addNotification(msg) {
    globalState.notifications.push({
      id: Date.now(),
      message: msg,
      read: false
    })
  }

  // readonly prevents direct modification
  return {
    state: readonly(globalState),
    setUser,
    setTheme,
    addNotification
  }
}

Changes go only through the methods, and an attempt to write state.theme = 'light' in a component ends with a console warning while the value stays unchanged. Usage in any component looks like this:

<!-- Any component - same state -->
<script setup>
import { useGlobalStore } from './composables/useGlobalStore'

// Both components see the same data
const { state, addNotification } = useGlobalStore()
</script>

<template>
  <p>Theme: {{ state.theme }}</p>
  <p>Notifications: {{ state.notifications.length }}</p>
</template>

The key difference: the state is defined outside the composable function, so every call to useGlobalStore() returns a reference to the same object. One caveat: with server-side rendering (SSR), such state would be shared by all users. That is why in large applications this role is taken over by Pinia, which you will meet in the Mission Database.

Event Bus with Reactivity

Vue 3 removed the $on and $off methods from the component instance, which were used to build a global event bus in Vue 2. We can, however, create a reactive event system - like the NOVA LAB station's communication network. The listeners map assigns a list of handler functions to each event name, and the lastEvent ref remembers the last signal. Both are created outside the function, as in the singleton, so all components broadcast on the same network:

import { ref } from 'vue'

// One network for the whole app - outside the function
const lastEvent = ref(null)
const listeners = new Map()

function useEventBus() {
  function emit(eventName, payload) {
    lastEvent.value = { name: eventName, payload, timestamp: Date.now() }

    const handlers = listeners.get(eventName) || []
    handlers.forEach(handler => handler(payload))
  }

  function on(eventName, handler) {
    if (!listeners.has(eventName)) {
      listeners.set(eventName, [])
    }
    listeners.get(eventName).push(handler)

    // Return unsubscribe function
    return () => {
      const handlers = listeners.get(eventName)
      const index = handlers.indexOf(handler)
      if (index > -1) handlers.splice(index, 1)
    }
  }

  return { lastEvent, emit, on }
}

If the map were created inside the function, every component would have its own private network, and signals from one module would never reach another. The on method returns a function that removes the handler from the list, and the component has to call it when it unmounts:

<script setup>
import { onUnmounted } from 'vue'

const { emit, on } = useEventBus()

// Subscription with automatic cleanup
const unsubscribe = on('sensor-alert', (data) => {
  console.log('Alert from sensor:', data)
})

onUnmounted(() => {
  unsubscribe() // Important! Prevents memory leaks
})

// Emitting an event
emit('sensor-alert', { sensorId: 'T-01', value: 45 })
</script>

Without unsubscribe, an unmounted component would stay in the map forever and keep reacting to alarms - a classic memory leak.

State Machine with ref and computed

State machines are an ideal pattern for managing complex state - like the station's safety protocols, where every state has precisely defined transitions. The machine keeps the current state in a ref and derives the list of allowed events with computed:

import { ref, computed } from 'vue'

function useStateMachine(config) {
  const currentState = ref(config.initial)

  const availableTransitions = computed(() => {
    const stateConfig = config.states[currentState.value]
    return stateConfig ? Object.keys(stateConfig.on || {}) : []
  })

  function transition(event) {
    const stateConfig = config.states[currentState.value]
    if (!stateConfig || !stateConfig.on || !stateConfig.on[event]) {
      console.warn(
        `Illegal transition: ${currentState.value} -> ${event}`
      )
      return false
    }

    const nextState = stateConfig.on[event]
    currentState.value = nextState
    return true
  }

  function canTransition(event) {
    return availableTransitions.value.includes(event)
  }

  return { currentState, availableTransitions, transition, canTransition }
}

The transition method rejects an event the current state doesn't allow and returns false instead of corrupting the data. All the knowledge about transitions lives in the configuration object, where each state's on field maps an event to a target state:

<script setup>
const experimentMachine = useStateMachine({
  initial: 'idle',
  states: {
    idle: {
      on: { START: 'running', CONFIGURE: 'configuring' }
    },
    configuring: {
      on: { SAVE: 'idle', CANCEL: 'idle' }
    },
    running: {
      on: { PAUSE: 'paused', COMPLETE: 'completed', FAIL: 'failed' }
    },
    paused: {
      on: { RESUME: 'running', ABORT: 'failed' }
    },
    completed: {
      on: { RESET: 'idle' }
    },
    failed: {
      on: { RESET: 'idle', RETRY: 'running' }
    }
  }
})

// Used in template
// experimentMachine.currentState.value => 'idle'
// experimentMachine.transition('START') => state changes to 'running'
// experimentMachine.canTransition('PAUSE') => true (we are now in 'running')
</script>

PAUSE cannot be triggered from the idle state, so you can disable the pause button with a simple :disabled="!experimentMachine.canTransition('PAUSE')".

Reactive Observer Pattern

The observer pattern with Vue reactivity - like a monitoring system where every sensor can have many observers. Each subscriber is a separate watch, and the function returned by watch stops it on demand:

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

function useObservable(initialValue) {
  const value = ref(initialValue)
  const history = ref([])
  const observers = ref(0)

  // Each watch is a new observer
  function subscribe(callback) {
    observers.value++
    const unwatch = watch(value, (newVal, oldVal) => {
      callback({ newVal, oldVal, timestamp: Date.now() })
    })

    return () => {
      unwatch()
      observers.value--
    }
  }

  function setValue(newValue) {
    history.value.push({
      from: value.value,
      to: newValue,
      timestamp: Date.now()
    })
    if (history.value.length > 100) history.value.shift()
    value.value = newValue
  }

  return {
    value: readonly(value),
    history: readonly(history),
    observers,
    subscribe,
    setValue
  }
}

The history keeps at most the 100 most recent changes, and we expose the value and the history as read-only. In the component there is one trap: the template automatically unwraps only top-level refs, not refs tucked inside a plain object. That's why we pull them out with destructuring:

<script setup>
import { onUnmounted } from 'vue'

const temperature = useObservable(22)
// Pull the refs to the top level so the template unwraps them
const { value: currentTemp, history, observers } = temperature

// Observer 1 - alarm
const unsub1 = temperature.subscribe(({ newVal }) => {
  if (newVal > 40) console.warn('Critical temperature!')
})

// Observer 2 - logging
const unsub2 = temperature.subscribe(({ newVal, oldVal }) => {
  console.log(`Temp: ${oldVal} -> ${newVal}`)
})

onUnmounted(() => {
  unsub1()
  unsub2()
})

// Changing the value notifies all observers
temperature.setValue(25)
</script>

<template>
  <p>Temperature: {{ currentTemp }}°C</p>
  <p>Active observers: {{ observers }}</p>
  <p>Change history: {{ history.length }}</p>
</template>

The panel shows 25°C, two observers and one change in the history, and the console prints "Temp: 22 -> 25". If you wrote temperature.history.length in the template, you would see an empty spot, because the nested ref would not be unwrapped.

My advice: before you reach for an event bus, check whether props and emits, provide/inject or a shared store are enough. The Vue documentation discourages a global bus in most situations, because the data flow becomes invisible. VueUse, which you will meet in the next lesson, even has a ready-made useEventBus. In the editor below, the singleton switches the theme, the state machine takes an experiment through its states, and the observed temperature notifies its subscribers.

Remember: a good pattern is a station protocol - it says who may change the state, when, and whom to notify about it.

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

// ===== REACTIVE SINGLETON =====
const globalState = {
  theme: ref('dark'),
  locale: ref('pl'),
  notifications: ref([])
}

function useGlobalStore() {
  function setTheme(t) { globalState.theme.value = t }
  function addNotification(msg) {
    globalState.notifications.value.push({ id: Date.now(), message: msg })
  }
  return {
    theme: globalState.theme,
    locale: globalState.locale,
    notifications: globalState.notifications,
    setTheme,
    addNotification
  }
}

// ===== STATE MACHINE =====
function useStateMachine(config) {
  const currentState = ref(config.initial)

  const availableTransitions = computed(() => {
    const sc = config.states[currentState.value]
    return sc ? Object.keys(sc.on || {}) : []
  })

  function transition(event) {
    const sc = config.states[currentState.value]
    if (!sc || !sc.on || !sc.on[event]) return false
    currentState.value = sc.on[event]
    return true
  }

  function canTransition(event) {
    return availableTransitions.value.includes(event)
  }

  return { currentState, availableTransitions, transition, canTransition }
}

// ===== REACTIVE OBSERVER =====
function useObservable(initialValue) {
  const value = ref(initialValue)
  const history = ref([])
  const observerCount = ref(0)

  function subscribe(callback) {
    observerCount.value++
    const unwatch = watch(value, (newVal, oldVal) => {
      callback({ newVal, oldVal })
    })
    return () => { unwatch(); observerCount.value-- }
  }

  function setValue(newValue) {
    history.value.push({ from: value.value, to: newValue, time: new Date().toLocaleTimeString() })
    if (history.value.length > 15) history.value.shift()
    value.value = newValue
  }

  return { value, history, observerCount, subscribe, setValue }
}

// === Instances ===
const store = useGlobalStore()

const experiment = useStateMachine({
  initial: 'idle',
  states: {
    idle: { on: { START: 'running', CONFIGURE: 'configuring' } },
    configuring: { on: { SAVE: 'idle', CANCEL: 'idle' } },
    running: { on: { PAUSE: 'paused', COMPLETE: 'completed', FAIL: 'failed' } },
    paused: { on: { RESUME: 'running', ABORT: 'failed' } },
    completed: { on: { RESET: 'idle' } },
    failed: { on: { RESET: 'idle', RETRY: 'running' } }
  }
})

const temperature = useObservable(22)

// Subscribe observers
const alerts = ref([])
temperature.subscribe(({ newVal }) => {
  if (newVal > 35) alerts.value.unshift('ALERT: Temp ' + newVal + '°C!')
  if (alerts.value.length > 5) alerts.value.pop()
})
temperature.subscribe(({ newVal, oldVal }) => {
  store.addNotification('Temp: ' + oldVal + ' -> ' + newVal)
})
</script>

<template>
  <div class="lab" :class="store.theme.value">
    <h1>Reactive Patterns - NOVA LAB</h1>

    <section>
      <h2>Singleton Store</h2>
      <p>Theme: {{ store.theme.value }} | Locale: {{ store.locale.value }}</p>
      <button @click="store.setTheme(store.theme.value === 'dark' ? 'light' : 'dark')">Toggle Theme</button>
      <div class="notifs">
        <div v-for="n in store.notifications.value.slice(-5)" :key="n.id" class="notif">{{ n.message }}</div>
      </div>
    </section>

    <section>
      <h2>State Machine - Experiment</h2>
      <div class="state-display">{{ experiment.currentState.value.toUpperCase() }}</div>
      <div class="transitions">
        <button v-for="t in experiment.availableTransitions.value" :key="t"
          @click="experiment.transition(t)" class="trans-btn">
          {{ t }}
        </button>
      </div>
      <p v-if="!experiment.availableTransitions.value.length" class="info">No transitions (terminal state)</p>
    </section>

    <section>
      <h2>Observable - Temperature</h2>
      <p>Value: {{ temperature.value.value }}°C | Observers: {{ temperature.observerCount.value }}</p>
      <div class="temp-controls">
        <button @click="temperature.setValue(temperature.value.value - 5)">-5°C</button>
        <button @click="temperature.setValue(temperature.value.value + 5)">+5°C</button>
        <button @click="temperature.setValue(Math.round(Math.random() * 50))">Random</button>
      </div>
      <div class="history">
        <div v-for="(h, i) in temperature.history.value.slice(-8)" :key="i" class="hist-item">
          {{ h.time }}: {{ h.from }}°C -> {{ h.to }}°C
        </div>
      </div>
      <div v-if="alerts.length" class="alerts">
        <div v-for="(a, i) in alerts" :key="i" class="alert">{{ a }}</div>
      </div>
    </section>
  </div>
</template>

<style scoped>
.lab { background: #0a0e27; color: #e0e0ff; padding: 1.5rem; min-height: 100vh; font-family: 'Courier New', monospace; transition: all 0.3s; }
.lab.light { background: #f0f0f5; color: #1a1a3f; }
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.5rem 1rem; border-radius: 4px; cursor: pointer; margin: 0.2rem; font-family: inherit; }
button:hover { background: #00ff88; color: #0a0e27; }
.state-display { font-size: 2rem; font-weight: bold; color: #00ff88; text-align: center; padding: 1rem; background: rgba(0,255,136,0.1); border: 2px solid #00ff88; border-radius: 8px; margin: 1rem 0; }
.transitions { display: flex; flex-wrap: wrap; gap: 0.5rem; justify-content: center; }
.trans-btn { background: #333; }
.trans-btn:hover { background: #00b4d8; }
.temp-controls { display: flex; gap: 0.5rem; margin: 0.5rem 0; }
.history { background: rgba(0,0,0,0.3); padding: 0.5rem; border-radius: 4px; margin: 0.5rem 0; }
.hist-item { font-size: 0.8rem; color: #aaa; padding: 0.2rem 0; }
.notifs { margin-top: 0.5rem; }
.notif { font-size: 0.8rem; color: #00b4d8; padding: 0.2rem 0; }
.alerts { margin-top: 0.5rem; }
.alert { background: rgba(255,0,85,0.15); border-left: 3px solid #ff0055; padding: 0.3rem 0.6rem; margin: 0.2rem 0; font-size: 0.85rem; color: #ff4444; }
.info { color: #666; font-style: italic; }
</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 does the Reactive Singleton pattern mean in composables?

  2. 2. What is the main advantage of the State Machine pattern with ref and computed?

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

Hands-on tasks in the game

  • Code editor

    Build useStateMachine with currentState (ref), availableTransitions (computed), transition() and canTransition(). Configuration as a parameter.

  • Vertical ordering

    Arrange the steps for creating a Reactive Singleton composable:

  • Click in order

    Arrange the steps for subscribing and emitting an event:

  • Code editor

    Build useObservable with value (ref), history (ref), subscribe() returning unsubscribe, setValue() and observers count.

  • Horizontal ordering

    Arrange the state transition call in a State Machine:

  1. QuestionReactive Singleton
  2. QuestionState Machine in Vue
  3. Coding taskPractice: State Machine Composable
  4. Put in orderReactive Singleton Lifecycle
  5. Questionreadonly in Singleton
  6. Click in orderUsing Event Bus Composable
  7. Coding taskPractice: Reactive Observer Pattern
  8. Put in orderTransition in State Machine

Useful articles