Lists and Keys in React 📝
What are the keys in React, and How and Why to use a unique Key for our lists🫡
Welcome to my yet another React blog where I have written everything about rendering Lists in React and the special “Key” prop. Bonus! — I have also included some Interview questions and answers that I came across in my interviews😁
- What is Lists? When are you going to use them?
You are bound to use Lists in your React application someday. It might be for displaying dynamic data, menus, shopping carts, or even in a simple Todo List! Basically, lists are used in almost all repeating structures. In React, Lists can be created in a similar way as we create lists in JavaScript. We use the “map()” function for traversing the list elements and enclosing them in “{ }” braces. React provides us with a “Key” prop to optimize the performance. The basic structure of lists in React will look like this —
{addItem.map((item) => (
<div className={inst.cartItem} key={item.id}>
// some repeated pattern I want
</div>
))}
2. Brief about Keys 🔑
If you are new to react, you might have come across the error — “Error : Warning: Each child in a list should have a unique "key" prop
” in the console. Key helps React to identify which items have been changed, updated, or deleted. React uses keys to pinpoint which of the elements in the list collection is changed and needs to be re-rendered instead of re-rendering the whole collection. This will help in boosting our React’s application performance. The best way to select a key is to use a string that can be identified uniquely. Most often you can use ID’s of your data as I have shown in the example above. Or alternatively, you can use an NPM package called uuid. Refer to the example below —
import { v4 } from "uuid";
export const Product = () => {
return (
<>
{Products.map((data) => (
<LinkContainer
to={`/products/some-link/${data.slug}`}
key={v4()}
>
// code
</LinkContainer>
))}
</>
)};
3. More about Keys 🔑
“Keys must only be unique among siblings”. Keys in React should not be globally unique, but they should be unique among their siblings. Hence we can use the same keys in different unrelated components. Very important to note that the Key is not passed to your component. The only purpose of the key is to serve as a hint. If a unique value is required for the component you have to use props. Example —
return(
<>
{result.map(()=>
<Product key={result.id} id={result.id} name={result.name} />
//some code
)}
</>
)
Some Interview Questions you might come across about Lists and Keys 🔥
- What are the keys in React?
- What happens when we don't use keys in our lists?
- Are keys helpful for React or developers?
- Should the keys be unique in the entire application?
- Can we pass the key as a prop?
That’s it for this blog 🫡Hope I covered all the important points about Lists and Keys in React. Let me know in the comments if I missed something 👇🏽Follow for more insightful blogs on React 🔥