DEV Community

Cover image for What Happens When You Don't Provide Keys in ReactJS?
Sanjampreet Singh
Sanjampreet Singh

Posted on • Edited on

What Happens When You Don't Provide Keys in ReactJS?

You've probably heard about the importance of using keys when rendering a list of components when working with ReactJS. But have you ever thought about what happens if you don't provide keys? Let's go over the consequences of not using keys in ReactJS and how to avoid common pitfalls.

What Are Keys in ReactJS?

To begin, Keys are a special attribute that assists React in determining which items in a list of components have changed, been added, or removed. React uses the key to keep track of each component's identity when rendering a list of components, and if the key is missing, React must search through the entire list to determine which component has changed.

What Happens When You Don't Use Keys?

React will have to rely on other methods to determine which component has changed in the absence of keys. This can lead to performance issues and even unexpected bugs.

Let's look at an example. Suppose we have a list of items that we want to render as a series of components. We can do this using the map function:

function ItemList({ items }) {
  return (
    <ul>
      {items.map(item => (
        <li>{item}</li>
      ))}
    </ul>
  );
}

Enter fullscreen mode Exit fullscreen mode

In this example, we are rendering a list of items as li components. However, we have not provided any keys for these components. Let's see what happens when we add or remove an item:

const items = ['Item 1', 'Item 2', 'Item 3'];

ReactDOM.render(<ItemList items={items} />, document.getElementById('root'));

// Add an item
items.push('Item 4');
ReactDOM.render(<ItemList items={items} />, document.getElementById('root'));

// Remove an item
items.pop();
ReactDOM.render(<ItemList items={items} />, document.getElementById('root'));
Enter fullscreen mode Exit fullscreen mode

In this example, the ItemList component is rendered with an initial set of items. Then we add and remove items from the list. However, because no keys have been provided, React is forced to re-render the entire list on each change, even if only one item has been added or removed. It can lead to a poor user experience. When rendering a list of items and the wrong item is updated, the user may be confused or frustrated by the unexpected behavior.

To avoid this problem, always provide unique keys for components in dynamic lists. This can be accomplished by using a unique identifier, such as an ID or a timestamp.

How to Avoid Common Pitfalls

To avoid these common pitfalls when rendering lists of components, ensure that each component in the list has a unique key. The key should ideally be a unique identifier for the component, such as a database or API response ID. If you don't have a unique identifier, you can use the array's index as a last resort.

function ItemList(props) {
  return (
    <ul>
      {props.items.map((item, index) => (
        <li key={item.id || index}>{item.text}</li>
      ))}
    </ul>
  );
}
Enter fullscreen mode Exit fullscreen mode

In the above example, we're using the item's id attribute as the key and falling back to the index, if id is not present. This ensures that each item has a unique key and allows React to update the list efficiently when changes occur.

Conclusion

Keys play an important part in rendering component lists in React. You can prevent typical issues like as duplicate keys, excessive re-rendering, and bad user experience by giving a unique key for each component. When rendering a list, always specify a key and utilise a unique identifier whenever possible.

Top comments (7)

Collapse
 
coursepilottech profile image
CoursePilot • Edited

This is well explained and so important when learning React!

Just one thing to add: should be careful when using the index number as the key. Sometimes it's not unique enough.

In my earlier days, I was building a drag and drop, time-tracker project management app and by using the index number instead of a more unique key like uuid or a complex enough timestamp, I experienced all kinds of issues. The wrong task was getting updated, the timer got all weird and it wasn't deleting properly.

I spent hours trying to come up with a solution and in the end, it was literally just because the index number was not unique enough in this particular case, due to the nature of drag and drop.

So the React key should not be taken lightly!

Collapse
 
sanjampreetsingh profile image
Sanjampreet Singh

Thanks CoursePilot πŸ˜ƒ

Collapse
 
ninhnd profile image
Dang Ninh

Simple and straightforward. I remember being asked the same question in an interview and back then I didn't really know the importance of that, just knew that "it yells at me for not doing that in the console log so I make the warning disappear πŸ˜…"

Collapse
 
sanjampreetsingh profile image
Sanjampreet Singh

Thanks πŸ™

Collapse
 
fersadilala profile image
Lora

Really? Thanks!

Collapse
 
amadujallow profile image
Amadu Jallow

Thanks so much for this

Collapse
 
sanjampreetsingh profile image
Sanjampreet Singh

Thanks for appreciation 😊