What is the key attribute in Vue?
Answer
The key attribute is a special hint for Vue's diffing algorithm that helps it identify which items in a list have changed, been added, or removed — enabling efficient DOM updates and correct component reuse. In v-for: always provide a unique :key when rendering lists: <li v-for="user in users" :key="user.id">{{ user.name }}</li>. Without :key, Vue uses an in-place patch strategy — it tries to reuse DOM nodes in place, which is efficient but can cause bugs with stateful components or inputs. With :key, Vue matches each element to its key — moved elements are preserved, new elements are created, removed elements are destroyed. When keys are critical: (1) List items with state (form inputs, component state) — without key, states get mixed up when list order changes; (2) Animated list transitions — keys track elements for enter/leave animations; (3) Conditionally rendered components — different keys force recreation. Using key to force re-render: change the key on any element/component to force it to be destroyed and recreated: <UserForm :key="userId" /> — when userId changes, the form is completely recreated (resetting all state). This is a useful pattern for resetting forms. Key uniqueness: keys only need to be unique among siblings, not globally. Never use the array index as a key if the list can be reordered or filtered — use stable unique identifiers.