ReactJS Tutorial

What Are Keys in ReactJS? What is Key Uniqueness?

Table of Contents

  • What is a Key in React?
  • Test your knowledge with a quick quiz!
  • How to use keys with components?
  • What is the Meaning of Uniqueness of Keys?

What is a Key in React?

A “key” is a special string attribute programmers should include when they create lists of elements in React. It is like an unique identifier for an element that helps identify items that have been changed, updated, or deleted from the Lists.

The benefits of using keys in ReactJS are reaped when components are created dynamically or when users make changes in the lists. Keys can also help you determine which components you sZhould re-render instead of re-rendering all components every time.

One of the best ways of assigning a key in React is to give them inside the array so that the elements have a stable identity. Strings are the best keys that you can use. Let’s understand this with an example.

Test your knowledge with a quick quiz!

What is the use of key prop in Component?

Select the correct answer

How to use keys with components?

Imagine a situation where there’s a separate component for list items and you need to extract list items from that component. In that case, you need to assign keys to the component you are returning from the iterator and not to the list items. 

In other terms, you must be assigning keys to and not to

  • If you want to avoid mistakes while assigning keys, always remember that you should assign keys to everything that you are returning from the inside of a map() function.

 

Let’s see examples of correct and incorrect usage of assigning Keys with components.

Incorrect usage:

What is the Meaning of Uniqueness of Keys?

It has been said time and again that keys assigned to the array elements must be unique. Now, this doesn’t mean that there cannot be two keys in the entire world. It just means that all the elements in a particular array must have unique keys. This implies that two different arrays can have the same set of keys.

Let’s look at an example.

Did you find this article helpful?