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) =>
  <Author
    key={author.id}
    id={author.id}
    blogs={author.blogs} />
);



Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #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
You might also like these
Revisiting variable scope in JavaScriptJavaScriptLearn to Establish Connection using MySQLi (object-oriented), MySQLi (procedural) and PDO with Example CodePHPWordPress: How to add a Search Icon in Menus with toggle effect using jQuery?jQueryHow to add navigation menu in Angular 9 app?AngularHow to add and remove list items using JavaScript?JavaScriptSelect statement in Postgres with examplesPostgres