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:

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 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
JavaScript Number MethodsJavaScriptIntroduction to components and templates Part 2: Templates and viewsAngularWhat’s the difference between visibility: hidden and display: none?CSSGap in Flex?CSSHow to add a ribbon on top of a container using CSS?CSS5 Key Principles Of Good Website UsabilityUI/UX