I know keys are important prop when using array in React. I'm just curious what happens if I don't specify a key for each list item. So I have a very simple case, where I have an array of buttons(react component) in a Dialog component. And those buttons won't change, but Dialog content may change. If I don't specify keys for each button, do my buttons get re-mount every time dialog content changes ? Is it good practice to ALWAYS include a key, even if it's redundant ?
Asked
Active
Viewed 2,708 times
2 Answers
1
Here is the official document's answer to your question! (https://reactjs.org/docs/reconciliation.html#recursing-on-children)

Tetsuya3850
- 947
- 1
- 7
- 15
1
React will default to using the index of an element as a key. If there is a chance that elements can move from their original places, you should set a key to avoid strange behaviour.
React documentation on keys links to this article that describes the bad behaviour.
Index as a key is an anti-pattern
Main point from that article:
Let me explain, a key is the only thing React uses to identify DOM elements. What happens if you push an item to the list or remove something in the middle? If the key is same as before React assumes that the DOM element represents the same component as before. But that is no longer true.

Kostas Minaidis
- 4,681
- 3
- 17
- 25

Gibrahh
- 173
- 2
- 7