YogeshChauhan . com

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:

amazon prime gift

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 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

How to use data-* Attributes in HTML?HTMLFull and Partial ROLLUP in Postgresql with ExamplesPostgresAll possible ways you can Insert Data in PostgresPostgresHow to add Date and Time picker in HTML and get the values using JavaScript?HTMLThe difference between Class declarations and Class expressions in JavaScriptJavaScriptThe difference between 400(4xx) and 500(5xx) errorsMisc