Home / Blog / Tips and Gotchas for Using key with v-for in Vue.js 3
Tips and Gotchas for Using key with v-for in Vue.js 3

Tips and Gotchas for Using key with v-for in Vue.js 3

Daniel Kelly
Daniel Kelly
Updated: December 6th 2024

When working with v-for in Vue 3, using the key attribute correctly is crucial for optimal performance and reactivity. In this article, we'll share valuable Vue tips to help you understand the best practices for using v-for key. You'll learn how to avoid common pitfalls and improve your app's rendering efficiency.

The v-for Key Attribute and Its Role in Vue Apps

When working with v-for loops in Vue apps it is typically recommended to provide a special key attribute. Something like this:

<div v-for="item in items" :key="item.id">

The purpose of this key attribute is to give a hint for the Vue virtual DOM algorithm to identify VNodes when diffing the new list of nodes against the old list.

The key attribute in Vue.js plays a critical role in helping Vue efficiently update the DOM. It allows Vue to identify which elements have changed, preventing unnecessary DOM manipulations, such as creating or moving elements, for optimized rendering.

Throughout my experience with Vue.js, I've encountered many misconceptions about the key attribute—and I’ve had my own share of misunderstandings too. In this article, I'll share valuable tips on how to use it correctly and, just as importantly, how NOT to use it.

Note that all the examples below assume each item in the array is an object, unless otherwise stated.

Should We Always Provide Keys to v-for?

My best advice when working with v-for in Vue.js is this: always provide a key whenever possible. This practice is strongly recommended by the official ESLint Plugin for Vue, which includes the vue/required-v-for-key rule. Following this guideline will help you avoid potential issues and improve the performance and stability of your Vue.js applications in the long run.

v-for Keys Should Be Unique

To use the key attribute correctly, it must always be unique for each item in the array being iterated over. If your data comes from a database, this is usually straightforward—just use the id, uid, or whatever unique identifier is available for your resource.

<div v-for="user in users" :key="user.id">

Avoid Using the Element Id for v-for Keys

What if the items in your array don’t include an id? In such cases, you can use another value that is guaranteed to be unique for each item.

<div v-for="user in users" :key="user.username">

If no single property is guaranteed unique, but a combination of several properties is, you can use JSON.stringify() to create a unique key.

<div v-for="user in users" :key="JSON.stringify(user)">

But what if no properties are unique? Is it acceptable to use the index?

No Indexes as Keys

You should avoid using array indexes as keys since indexes represent an item's position in the array, not the item’s unique identity.

❌ <div v-for="(user, index) in users" :key="index">

Why is this important? If a new item is inserted into the array at any position other than the end, Vue will update the DOM, but the local data in the iterated component won’t sync correctly with the new data.

This issue is easier to understand with an example. In the Stackblitz below, there are two identical lists—one using index as the key and the other using user.name. The "Add New After Robin" button inserts Cat Woman into the middle of the list. Try it out and compare how the two lists behave.

Notice how the local data is now completely mismatched in the first list. This is the problem when using :key="index".

What About Leaving the v-for Key Off Completely?

Here’s a crucial point: leaving the key off is essentially the same as using :key="index". Both approaches lead to the same issue. The only difference is that without the key, you're not under the false impression that you’ve protected the DOM from reactivity problems.

So, once again, we should follow the ESLint rule and ensure that every v-for iteration uses a unique key.

However, we still face the challenge of dealing with cases where nothing is inherently unique about our items.

What to Do When Nothing is Uniquely Identifiable

This is where many developers face challenges. Let's approach this from a different angle: When is it acceptable not to provide a key? There are a few situations where omitting the key is technically permissible:

  • The items being iterated over don't render components or DOM elements that require local state (like component data or input values).
  • The items won't be reordered or dynamically modified (such as adding new items except at the end of the list).

While these cases may seem valid, they can often change as features evolve. So, even in these situations, omitting the key could still lead to issues as your app grows and changes.

Conclusion

In conclusion, with all that we now know my final recommendation would be to:

Leave off key when:

  • You have nothing unique AND
    • You are quickly testing something out
    • It's a simple demonstration of v-for
    • or you are iterating over a simple hard-coded array (not dynamic data from a database, etc)

Include key:

  • Whenever you've got something unique
  • You're iterating over more than a simple hard coded array
  • and even when there is nothing unique but it's dynamic data (in which case you need to generate random unique id's)

If you'd like more tips on dealing with other common gotchas in Vue.js checkout our course Common Mistkes in Vue.js and How to Avoid Them (it's 100% FREE 🔥) . Also, I've given a conference talk on this very subject. Watch the video of it on YouTube.

Related Courses

Start learning Vue.js for free

Daniel Kelly
Daniel Kelly
Daniel is the lead instructor at Vue School and enjoys helping other developers reach their full potential. He has 10+ years of developer experience using technologies including Vue.js, Nuxt.js, and Laravel.

Comments

Latest Vue School Articles

Vue.js Testing with Vue Test Utils and Vitest

Vue.js Testing with Vue Test Utils and Vitest

For inexperienced testers, Vue.js testing can be intimidating. But Vitest and Vue Test Utils makes testing Vue components a breeze!
Daniel Kelly
Daniel Kelly
Building Advanced WYSIWYG Editors with Vue and TinyMCE &#8211; A Complete Guide

Building Advanced WYSIWYG Editors with Vue and TinyMCE – A Complete Guide

Learn to integrate and customize TinyMCE in Vue with the course 'Rich Text Editing and Beyond with TinyMCE and Vue.' From basic WYSIWYG setups to advanced CMS and CRM solutions, this hands-on course equips you with the tools to build powerful content editing applications.
Daniel Kelly
Daniel Kelly

Our goal is to be the number one source of Vue.js knowledge for all skill levels. We offer the knowledge of our industry leaders through awesome video courses for a ridiculously low price.

More than 200.000 users have already joined us. You are welcome too!

Follow us on Social

© All rights reserved. Made with ❤️ by BitterBrains, Inc.