How does Vue update the DOM when data changes?
How Vue updates the DOM when data changes
Vue uses a reactive system and a Virtual DOM to automatically and efficiently update the user interface when data changes.
1. Data reactivity
When you create state (for example, in data() or with ref()/reactive() in the Composition API), Vue wraps the object in a Proxy.
This Proxy intercepts property read and write operations.
const state = reactive({
count: 0
})If you then do:
state.count++Vue "sees" the change and schedules an update for all components that depend on state.count.
2. Dependency tracking
Vue tracks which data is used while rendering a component.
When a component is first rendered, Vue registers all reactive properties that were read inside the template or the render() function.
Example:
<template>
<p>Counter: {{ count }}</p>
</template>
<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>When Vue renders the template, it "remembers" that the component depends on count.
Now, when count.value changes, Vue re-renders only this component.
3. Virtual DOM
Vue does not modify the DOM directly. Instead:
- It generates a virtual tree of elements (Virtual DOM) - a lightweight JS representation of the current interface.
- When data changes, Vue creates a new virtual tree.
- Then Vue compares (diffs) the new tree against the old one.
- And updates the real DOM with only the minimally necessary changes.
This makes updates very fast and efficient.
4. Batching (grouping updates)
Vue does not update the DOM instantly on every data change. Changes are collected and executed asynchronously on the next "tick" (event loop iteration), to avoid unnecessary re-renders.
count.value++
count.value++
console.log('DOM not updated yet')
await nextTick()
console.log('DOM already updated')5. Minimal DOM updates
Thanks to the Virtual DOM and dependency tracking, Vue:
- Does not re-render the whole component;
- Does not touch other independent parts of the page;
- Changes only what actually changed.
Summary
Vue updates the DOM reactively and efficiently:
- Tracks which data is used where;
- Recomputes only the necessary components when data changes;
- Uses the Virtual DOM for minimal changes to the real DOM;
- Performs updates asynchronously for optimal performance.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.