Vue.js course · Module 9: Composables & VueUse
Performance and Composable Optimization
In this lesson5
At the NOVA LAB station every watt of energy counts - and in Vue applications every unnecessary render and computation is wasted performance. The problem usually isn't visible right away: a panel with ten sensors runs smoothly, but with ten thousand readings it starts to stutter, and a forgotten timer eats memory after an hour of work. Let's learn composable optimization techniques and find out which of them really help.
shallowRef - Shallow Reactivity
ref() creates deep reactivity - Vue wraps every nested object and tracks changes to every field. shallowRef() reacts only to a change of the whole value, not its inner properties, so it saves work with large data. The difference is easiest to see on an array:
import { shallowRef, triggerRef } from 'vue'
// Large data list - shallowRef is more efficient
const sensorReadings = shallowRef([])
// This will NOT trigger an update (shallow reactivity)
sensorReadings.value.push({ id: 1, temp: 22 })
// This will trigger an update - assigning a new array
sensorReadings.value = [...sensorReadings.value, { id: 1, temp: 22 }]
// Alternatively: manually trigger an update
sensorReadings.value.push({ id: 2, temp: 23 })
triggerRef(sensorReadings) // Force updateAfter push the array really does contain a new element, but Vue doesn't know about it and the screen doesn't refresh. A new array assigned to .value or a call to triggerRef tells Vue about the change. A composable for large datasets therefore follows one rule: every operation creates a new array:
<script setup>
import { shallowRef, triggerRef, computed } from 'vue'
// Efficient composable for large datasets
function useLargeDataset() {
const items = shallowRef([])
const count = computed(() => items.value.length)
function addItem(item) {
// Create a new array - triggers reactivity
items.value = [...items.value, item]
}
function addMany(newItems) {
// One assignment and one array copy instead of N
items.value = [...items.value, ...newItems]
}
function removeItem(id) {
items.value = items.value.filter(item => item.id !== id)
}
function updateItem(id, updates) {
items.value = items.value.map(item =>
item.id === id ? { ...item, ...updates } : item
)
}
return { items, count, addItem, addMany, removeItem, updateItem }
}
</script>filter and map return new arrays by nature, so they fit shallowRef perfectly. addMany adds the whole batch with a single assignment - calling addItem in a loop would copy the entire, growing array on every iteration.
When to use shallowRef:
- Large arrays (hundreds or thousands of elements)
- Objects with deep nesting
- Data you change rarely or as a whole
Computed Caching
Computed properties are cached automatically - they are recalculated only when their dependency changes. This is a key optimization. In the composable below we compare computed with a plain function called in the template:
import { ref, computed } from 'vue'
function useFilteredExperiments() {
const experiments = ref([])
const searchQuery = ref('')
const category = ref('all')
// GOOD: computed is cached
// Recalculates ONLY when experiments, searchQuery or category changes
const filtered = computed(() => {
console.log('Recalculating filtered experiments') // logs rarely
let result = experiments.value
if (searchQuery.value) {
const q = searchQuery.value.toLowerCase()
result = result.filter(e =>
e.name.toLowerCase().includes(q)
)
}
if (category.value !== 'all') {
result = result.filter(e => e.category === category.value)
}
return result
})
// BAD: function recalculates on every render
function getFiltered() {
console.log('Recalculating every time!') // logs frequently
return experiments.value.filter(e =>
e.name.toLowerCase().includes(searchQuery.value.toLowerCase())
)
}
// GOOD: chaining computed in a pipeline
const stats = computed(() => ({
total: filtered.value.length,
active: filtered.value.filter(e => e.status === 'active').length,
completed: filtered.value.filter(e => e.status === 'completed').length
}))
return { experiments, searchQuery, category, filtered, stats }
}If the template reads filtered five times in one render, the filter runs once, and on the next render with no change in the data - not at all. getFiltered() in the template recalculates on every call. stats uses the ready-made filtered, so the chain doesn't repeat the filtering.
watchEffect vs watch - Performance
watch and watchEffect differ not only in API, but also in what they track. watchEffect registers as dependencies the reactive values it actually read during its last run, while watch tracks only the source given as its first argument:
import { ref, watch, watchEffect } from 'vue'
const temperature = ref(22)
const pressure = ref(101)
const humidity = ref(45)
// watchEffect - tracks what it read during its last run
// temperature: always; pressure: only when temperature > 30;
// humidity: never, because the effect does not read it
watchEffect(() => {
console.log('watchEffect:', temperature.value)
// pressure becomes a dependency only when
// the condition is met and this line runs
if (temperature.value > 30) {
console.log('Pressure:', pressure.value)
}
})
// watch - tracks ONLY the specified source
// Fires ONLY on temperature change
watch(temperature, (newTemp) => {
console.log('watch:', newTemp)
// You can read other refs without creating dependencies
if (newTemp > 30) {
console.log('Pressure:', pressure.value)
}
})In practice it looks like this: at 22°C a pressure change doesn't trigger watchEffect, a humidity change never triggers it, and once the temperature rises to 35°C the effect starts reacting to pressure too. watch fires only on temperature changes the whole time.
Rule: use watch when you need to react to specific changes. Use watchEffect when you want automatic tracking of multiple dependencies.
Memory Leaks in Composables
One of the most common problems - uncleaned resources cause memory leaks. A leak happens in four steps: the composable starts a setInterval in onMounted, the component is unmounted, the timer keeps ticking and holds a reference to the state, and the memory cannot be freed. Compare both versions:
import { ref, onMounted, onUnmounted, watch } from 'vue'
// BAD - memory leak!
function useLeakyTimer() {
const seconds = ref(0)
onMounted(() => {
setInterval(() => { // Never cleaned up!
seconds.value++
}, 1000)
})
return { seconds }
}
// GOOD - proper cleanup
function useSafeTimer() {
const seconds = ref(0)
const isRunning = ref(false)
let intervalId = null
function start() {
if (isRunning.value) return
isRunning.value = true
intervalId = setInterval(() => {
seconds.value++
}, 1000)
}
function stop() {
if (!isRunning.value) return
isRunning.value = false
clearInterval(intervalId)
intervalId = null
}
// Always clean up in onUnmounted
onUnmounted(() => {
if (intervalId) {
clearInterval(intervalId)
}
})
return { seconds, isRunning, start, stop }
}Every mount of the "BAD" version adds another immortal timer. The same rule applies to network requests: a response that arrives after the component unmounts has nowhere to go. The browser's AbortController lets you cancel a fetch - you pass its signal to the request, and abort() cancels it in onUnmounted:
import { ref, onMounted, onUnmounted } from 'vue'
function useSensorFeed(url) {
const data = ref(null)
const loading = ref(false)
const error = ref(null)
let controller = null
async function fetchData() {
controller = new AbortController()
loading.value = true
error.value = null
try {
const response = await fetch(url, { signal: controller.signal })
data.value = await response.json()
} catch (e) {
if (e.name !== 'AbortError') error.value = e.message
} finally {
loading.value = false
}
}
onMounted(() => fetchData())
onUnmounted(() => controller?.abort())
return { data, loading, error, fetchData }
}An aborted fetch ends with an error named AbortError, which we deliberately skip, because it is not a failure but our own decision. The order of steps is always the same: refs, the fetching function, the call in onMounted, the abort in onUnmounted and returning the API.
Composable Performance Checklist
The table below gathers the techniques from this lesson:
| Technique | When to use |
|---|---|
shallowRef | Large arrays/objects, infrequent updates |
computed instead of functions | Value depends on reactive state |
watch instead of watchEffect | Specific source to observe |
Cleanup in onUnmounted | Timers, event listeners, WebSocket, fetch |
| Batch updates | Vue merges changes from one tick itself; with shallowRef replace the whole value once |
triggerRef | Mutating shallowRef without creating a copy |
The batch updates row needs an explanation, because a popular myth surrounds it. Vue buffers DOM updates until the next tick, so the component renders once, no matter how many fields you change in one function:
// Batch updates - Vue merges changes from one tick anyway
import { ref } from 'vue'
function useBatchUpdate() {
const data = ref({ temp: 0, pressure: 0, humidity: 0 })
// Three mutations in one tick - still 1 render
function updateFields(temp, pressure, humidity) {
data.value.temp = temp
data.value.pressure = pressure
data.value.humidity = humidity
}
// Replacing the whole object - also 1 render
// (the only way if data were a shallowRef)
function replaceData(temp, pressure, humidity) {
data.value = { temp, pressure, humidity }
}
return { data, updateFields, replaceData }
}Both functions cause a single render, which is easy to check with a render counter. A difference appears only with a watcher using the flush: 'sync' option, which fires three times for updateFields, and with shallowRef, where a change to a single field would not be noticed at all.
My advice: don't optimize in advance. Start with a plain ref and computed, and switch to shallowRef when a measurement shows a problem with large data. Never postpone the cleanup in onUnmounted, though - that is not an optimization, it is a duty. In the editor below you will compare ref and shallowRef on update counters, see the computed cache at work and run a timer with and without a leak.
Remember: an efficient station doesn't recalculate what it already knows, and always turns off the lights in a module it leaves.
Code for this lesson: App.vue
<script setup>
import { ref, shallowRef, computed, watch, triggerRef, onUnmounted } from 'vue'
// ===== PERFORMANCE DEMO =====
// 1. shallowRef vs ref comparison
const regularItems = ref([])
const shallowItems = shallowRef([])
const renderCounts = ref({ regular: 0, shallow: 0 })
// Track renders
watch(regularItems, () => { renderCounts.value.regular++ }, { deep: true })
watch(shallowItems, () => { renderCounts.value.shallow++ })
function addToRegular() {
regularItems.value.push({ id: Date.now(), temp: Math.random() * 50 })
// Each push triggers deep watch
}
function addToShallow() {
// Must create new array for shallowRef to react
shallowItems.value = [...shallowItems.value, { id: Date.now(), temp: Math.random() * 50 }]
}
function addBatchToShallow(count) {
const newItems = Array.from({ length: count }, (_, i) => ({
id: Date.now() + i, temp: Math.random() * 50
}))
// One update for all items
shallowItems.value = [...shallowItems.value, ...newItems]
}
// 2. Computed caching demo
const experiments = ref([
{ name: 'Soil Analysis', category: 'geology', status: 'active' },
{ name: 'Atmosphere Test', category: 'atmosphere', status: 'completed' },
{ name: 'Water Search', category: 'geology', status: 'active' },
{ name: 'Radiation Scan', category: 'safety', status: 'active' },
{ name: 'Plant Growth', category: 'biology', status: 'completed' }
])
const searchQuery = ref('')
const computedCallCount = ref(0)
// Computed: cached, recalculates only when dependency changes
const filteredExperiments = computed(() => {
computedCallCount.value++ // Count calls
if (!searchQuery.value) return experiments.value
return experiments.value.filter(e =>
e.name.toLowerCase().includes(searchQuery.value.toLowerCase())
)
})
// Access filteredExperiments multiple times - computed is cached
const filteredCount = computed(() => filteredExperiments.value.length)
const activeFiltered = computed(() =>
filteredExperiments.value.filter(e => e.status === 'active')
)
// 3. Memory leak demo
const timerSeconds = ref(0)
let leakyInterval = null
const leakyIntervals = ref(0)
function createLeakyTimer() {
// BAD: no cleanup reference saved properly
leakyInterval = setInterval(() => { timerSeconds.value++ }, 1000)
leakyIntervals.value++
}
function createSafeTimer() {
if (leakyInterval) clearInterval(leakyInterval)
leakyInterval = setInterval(() => { timerSeconds.value++ }, 1000)
}
function stopTimer() {
if (leakyInterval) {
clearInterval(leakyInterval)
leakyInterval = null
}
timerSeconds.value = 0
}
onUnmounted(() => {
if (leakyInterval) clearInterval(leakyInterval)
})
</script>
<template>
<div class="perf-lab">
<h1>Performance Optimization - NOVA LAB</h1>
<section>
<h2>shallowRef vs ref</h2>
<div class="compare">
<div class="col">
<h3>ref (deep)</h3>
<p>Items: {{ regularItems.length }} | Renders: {{ renderCounts.regular }}</p>
<button @click="addToRegular">Add Item</button>
<button @click="regularItems = []">Clear</button>
</div>
<div class="col">
<h3>shallowRef (shallow)</h3>
<p>Items: {{ shallowItems.length }} | Renders: {{ renderCounts.shallow }}</p>
<button @click="addToShallow">Add Item</button>
<button @click="addBatchToShallow(10)">Add 10 (batch)</button>
<button @click="shallowItems = []">Clear</button>
</div>
</div>
</section>
<section>
<h2>Computed Caching</h2>
<input v-model="searchQuery" placeholder="Search experiments..." class="search" />
<p class="stats">
Computed calls: {{ computedCallCount }} |
Filtered: {{ filteredCount }} |
Active: {{ activeFiltered.length }}
</p>
<div v-for="e in filteredExperiments" :key="e.name" class="exp-item" :class="e.status">
{{ e.name }} <span class="cat">[{{ e.category }}]</span>
<span class="status-tag">{{ e.status }}</span>
</div>
</section>
<section>
<h2>Memory Leak Prevention</h2>
<p>Timer: {{ timerSeconds }}s | Active intervals: {{ leakyIntervals }}</p>
<div class="btns">
<button @click="createLeakyTimer" class="bad">Leaky Timer (BAD)</button>
<button @click="createSafeTimer" class="good">Safe Timer (GOOD)</button>
<button @click="stopTimer">Stop All</button>
</div>
<p class="hint">Try clicking "Leaky Timer" multiple times - each creates a NEW interval without clearing the old one!</p>
</section>
</div>
</template>
<style scoped>
.perf-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; margin-top: 2rem; }
h3 { color: #00ff88; margin: 0 0 0.5rem; }
section { margin: 1.5rem 0; }
.compare { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
.col { background: rgba(0,180,216,0.1); border: 1px solid #00b4d8; border-radius: 8px; padding: 1rem; }
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.bad { background: #ff0055; }
button.bad:hover { background: #ff4444; color: #fff; }
button.good { background: #00ff88; color: #0a0e27; }
.search { width: 100%; background: #1a1e3f; border: 1px solid #00b4d8; color: #fff; padding: 0.6rem; border-radius: 4px; margin: 0.5rem 0; font-family: inherit; }
.stats { color: #00b4d8; font-size: 0.9rem; }
.exp-item { padding: 0.5rem; margin: 0.3rem 0; background: rgba(0,0,0,0.3); border-radius: 4px; display: flex; align-items: center; gap: 0.5rem; }
.exp-item.active { border-left: 3px solid #00ff88; }
.exp-item.completed { border-left: 3px solid #888; opacity: 0.7; }
.cat { color: #888; font-size: 0.8rem; }
.status-tag { margin-left: auto; font-size: 0.75rem; padding: 0.15rem 0.5rem; border-radius: 10px; background: rgba(0,255,136,0.2); color: #00ff88; }
.exp-item.completed .status-tag { background: rgba(136,136,136,0.2); color: #888; }
.btns { display: flex; gap: 0.5rem; margin: 0.5rem 0; }
.hint { color: #ffb400; font-size: 0.8rem; font-style: italic; margin-top: 0.5rem; }
</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. When do we use shallowRef() instead of ref()?
2. What is the main advantage of computed() over a regular function?
These are 2 of 5 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Create a shallowRef for a sensor list. Add addMany() that creates a new array instead of push. Compare with ref.
- Vertical ordering
Arrange the steps of how a memory leak happens in useLeakyTimer:
- Click in order
Arrange a correct batch update for shallowRef:
- Code editor
Use computed() for filtered and stats instead of functions. Show that computed does not recalculate without a dependency change.
- Horizontal ordering
Arrange the correct removal of an element from shallowRef:
Tasks after this lesson
- QuestionshallowRef vs ref
- QuestionComputed Caching
- Coding taskPractice: shallowRef with Batch Update
- Put in orderHow a Memory Leak Happens in a Composable
- QuestiontriggerRef with shallowRef
- Click in orderBatch Update with shallowRef
- Coding taskPractice: Composable with Computed Caching
- QuestionPerformance: watch vs watchEffect
- Put in orderCreating a New Array in shallowRef
- QuestionPreventing Memory Leaks