0
0
Vueframework~8 mins

Key attribute and why it matters in Vue - Performance & Optimization

Choose your learning style9 modes available
Performance: Key attribute and why it matters
HIGH IMPACT
This affects how Vue efficiently updates the DOM during re-rendering, impacting interaction responsiveness and visual stability.
Rendering a list of items with dynamic updates
Vue
<template>
  <ul>
    <li v-for="item in items" :key="item.id"> {{ item.name }} </li>
  </ul>
</template>
Using a unique stable key like item.id lets Vue track each element precisely, minimizing DOM operations and preventing layout shifts.
📈 Performance GainSingle reflow per update, reduces repaints, improves INP and CLS scores.
Rendering a list of items with dynamic updates
Vue
<template>
  <ul>
    <li v-for="(item, index) in items" :key="index"> {{ item.name }} </li>
  </ul>
</template>
Using the array index as key causes Vue to reuse DOM nodes incorrectly when items change order or are added/removed, triggering unnecessary re-renders and layout shifts.
📉 Performance CostTriggers multiple reflows and repaints on list updates, increasing INP and causing CLS.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Using index as keyMany node removals and insertionsMultiple reflows per updateHigh paint cost due to layout shifts[X] Bad
Using unique id as keyMinimal node updatesSingle reflow per updateLow paint cost, stable layout[OK] Good
Rendering Pipeline
Vue uses the key attribute to map virtual DOM nodes to real DOM elements. When keys are unique and stable, Vue can patch only changed nodes, avoiding full re-renders.
Virtual DOM Diffing
DOM Update
Layout
Paint
⚠️ BottleneckLayout stage due to unnecessary DOM node removals and insertions when keys are unstable.
Core Web Vital Affected
INP, CLS
This affects how Vue efficiently updates the DOM during re-rendering, impacting interaction responsiveness and visual stability.
Optimization Tips
1Always use unique, stable keys for list items in Vue.
2Avoid using array index as key when list order can change.
3Proper keys reduce reflows, repaints, and layout shifts improving INP and CLS.
Performance Quiz - 3 Questions
Test your performance knowledge
Why should you avoid using array index as a key in Vue lists?
ABecause it makes the code shorter and harder to read
BBecause Vue does not support index as key
CBecause it can cause unnecessary DOM updates and layout shifts when list items change order
DBecause it increases the bundle size
DevTools: Performance
How to check: Record a performance profile while updating the list. Look for excessive Layout and Recalculate Style events.
What to look for: High number of Layout events and long scripting times indicate poor key usage causing reflows and repaints.