Skip to content

Instantly share code, notes, and snippets.

@drumnickydrum
Last active January 29, 2023 19:34
Show Gist options
  • Save drumnickydrum/28c951c3d7c35f25187dc3aded0a8c71 to your computer and use it in GitHub Desktop.
Save drumnickydrum/28c951c3d7c35f25187dc3aded0a8c71 to your computer and use it in GitHub Desktop.
[React: Rules of keys] Must do's for keys when rendering array items #react #keys

https://beta.reactjs.org/learn/rendering-lists#rules-of-keys

Rules of keys

  • Keys must be unique among siblings. However, it’s okay to use the same keys for JSX nodes in different arrays.
  • Keys must not change or that defeats their purpose! Don’t generate them while rendering.

Pitfall

You might be tempted to use an item’s index in the array as its key. In fact, that’s what React will use if you don’t specify a key at all. But the order in which you render items will change over time if an item is inserted, deleted, or if the array gets reordered. Index as a key often leads to subtle and confusing bugs.

Similarly, do not generate keys on the fly, e.g. with key={Math.random()}. This will cause keys to never match up between renders, leading to all your components and DOM being recreated every time. Not only is this slow, but it will also lose any user input inside the list items. Instead, use a stable ID based on the data.

Note that your components won’t receive key as a prop. It’s only used as a hint by React itself. If your component needs an ID, you have to pass it as a separate prop: <Profile key={id} userId={id} />.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment