React·100 questions

Why do we need the key prop in lists?

Answer

The special key attribute is a crucial rendering optimization tool in React lists that helps the library precisely identify which specific elements have been modified, added, or removed. When data in a list updates, React compares the old and new virtual element trees using a reconciliation algorithm, and having unique keys allows this process to be as fast as possible.

If you do not use keys or specify them incorrectly, application performance drops noticeably, and the user interface begins to behave with bugs. The most common developer mistake is using the array element's ordinal index as a key. This is only acceptable for static lists that are never sorted, filtered, or modified during the application's lifecycle.

When reordering elements or deleting a row from the middle of an array using index keys, React can get confused and mix up components with similar states. This leads to unpleasant visual bugs where data inside input fields is reset or displayed for the wrong users, causing a desynchronization between the component's state and its actual display on the screen.

To work correctly with lists, it is recommended to follow these rules:

Always use unique stable identifiers coming from the backend as keys, such as database user IDs like uuid.
Ensure that the key value remains unchanged throughout the component's lifecycle and is unique among neighboring list items.
Avoid generating random numbers right during rendering as keys, as this will force React to completely recreate DOM elements at every step, negating all optimization.
Was this answer helpful?

More questions in this topic

Related questions from other topics