React·100 questions

How to correctly write keys and identifiers for components?

Answer

The correct organization of identifiers and keys for elements in React components is critical for the stable operation of the entire virtual DOM architecture. The special key attribute should be used exclusively when rendering lists of elements via iteration methods. The main purpose of this parameter is to help the reconciliation algorithm accurately determine which specific elements were added, removed, or modified during the application's runtime. This minimizes the number of manipulations with the real DOM tree and ensures high rendering performance.

You must use unique and stable identifiers as key values that come directly from the source data of your business logic, such as unique string identifiers of database records. It is strictly prohibited to use random generators or the current timestamp as keys. Creating a new random identifier on each render cycle forces the library to assume that absolutely every list item has been replaced with a new one, which completely destroys the component cache, causes the local state to reset, and leads to a catastrophic drop in performance.

Another common mistake made by beginners is using the element's index in the array as a unique key. This approach is only permissible if your list is completely static, never changes its order, does not involve removing elements from the middle, and is not filtered. If list items can be rearranged, sorted, or deleted, using indices as keys will lead to critical bugs. React will bind the component's internal state to its position rather than its content, which may cause the user to see data from a completely different element.

Incorrectly formed or missing keys inevitably break the logic of saving the local state of controlled form elements and transition animations. When keys are violated, components lose their identity when the sorting order changes, which manifests as incorrect input behavior, resetting of the input focus, and visual interface artifacts. By paying due attention to the design of stable identifiers at the data architecture development stage, you completely eliminate a whole class of elusive UI bugs.

Was this answer helpful?

More questions in this topic

Related questions from other topics