Yogesh Chauhan's Blog

What are keys in React?

in React on May 10, 2021

You can render lists without components in React. But if you want to pass parameters and render the list items and make the block reusable then it’s a good practice to use components.

in my point of view, “keys” in React are like trackers. They help React identify stats of list items — changed, added or removed.

To give elements a stable identity, the keys should be assigned to the elements inside the array.

Just like this example from render lists inside a component post:

There is no complex math behind choosing a key for the list elements. Just add a key that can be used to easily identify each list items from their siblings.

Most of the time, you might end up using IDs from the data. For e.g. nameOfArray.id.

Try not to use indexes for keys if you are aware of the fact that the order of items might change.

Keys Should Be Unique

The keys you use must be unique among their sibling elements. You can use same keys for two different arrays — meaning they don’t need to be unique globally.

We can modify the example above like this:

As you can see in the example above, there are two instances of adding keys and both of those keys are same.

Think of keys as just a hint that you sent to React but they don’t get passed to the actual components. So, you need to additionally pass the ID if you want the IDs to render.

Just like this:

In this example, you can not access props.key but you can access props.id.

const listing = authors.map((author) =>
    blogs={author.blogs} />

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface #Jan 14 How to display a student’s individual transcript in Colleague? #Jan 11 How to install PuTTY on a MacOS?
You might also like these
How to animate list items using CSS and JavaScript?CSSHow to add a Pie Chart in Angular App?AngularIntroduction to components and templates Part 2: Templates and viewsAngularCONCAT and CONCAT_WS Functions in PostgresPostgresHow to add transparent text on top of an image using CSS?CSSHow to float an image around texts?CSS