How to Update React Keys in React

React uses the key attribute to identify which elements in a list have changed, been added, or been removed. While you do not directly “update” a key of an existing, mounted element, you can change a component’s key value dynamically to force React to discard the old component and mount a brand-new one. This article explains how to change React keys to force component resets and how to correctly update keys when rendering dynamic lists.

Forcing a Component Reset by Changing the Key

In React, if you change the key of a component, React treats it as a completely new component. It will unmount the old component, destroying its state, and mount a new one with the updated key. This is a powerful technique when you want to reset a component’s internal state automatically.

To do this, bind the key attribute to a state variable. When you update that state, the key updates, and the component resets:

import { useState } from 'react';

function Profile({ userId }) {
  // By using userId as the key, this entire component 
  // resets its internal state whenever the userId changes.
  return <ProfileDetails key={userId} userId={userId} />;
}

In this example, whenever userId changes, the ProfileDetails component is completely recreated, ensuring no stale state from the previous user remains.

Updating Keys in Dynamic Lists

When rendering arrays of data, you must update your keys when the underlying data changes. React relies on stable keys to map array items to DOM elements efficiently.

1. Use Unique Identifiers

Always map your keys to a unique, stable property from your data source, such as a database ID. When the data updates (e.g., adding, sorting, or deleting items), React uses these stable keys to determine exactly which elements to modify.

function TodoList({ todos }) {
  return (
    <ul>
      {todos.map(todo => (
        // Use a stable database ID as the key
        <li key={todo.id}>{todo.text}</li>
      ))}
    </ul>
  );
}

2. Avoid Dynamic Random Keys

Never generate random keys (like key={Math.random()}) during rendering. Doing so will cause React to recreate every single list item on every render. This leads to extremely poor performance, loss of input focus, and broken transitions.

3. Use Indexes as a Last Resort

Only use the array index as a key if the list is static (it will never be reordered, filtered, or appended to) and the items do not have unique IDs. If the list can change, using the index as a key will cause rendering bugs and state mismatches when items are updated.