Importance of keys in React

Wednesday, June 16, 20213 min read

Keys help React identify which items have changed, they should be given to the elements inside the array to give the elements a identity.

A key is a special string attribute you need to include when creating lists of elements.

React uses the key to match children in the original tree with children in the subsequent tree.

1[1, 2, 3, 4, 5].map((number) => (
2 <li key={number.toString()}>{number}</li>
3);

So, looking to that example, our first thought is that everything is fine, (at least we have no errors on the console) and in fact is totally fine, if the order of items never change.

For other words, if you are working with a list that order of items may change and if you use the item index as a key this can negatively impact performance and may cause issues with component state.

To get a better understanding of what I mean, let's implement a demo with 3 different approaches.

1const App = () => {
2 const ORDER = {
3 DESC: 'desc',
4 ASC: 'asc',
5 };
6
7 const [order, setOrder] = React.useState(ORDER.DESC);
8 const [items, setItems] = React.useState([
9 { id: 'POR', name: 'Portugal', population: 10000000 },
10 { id: 'GER', name: 'Germany', population: 83000000 },
11 { id: 'ITA', name: 'Italy', population: 60000000 },
12 { id: 'FRA', name: 'France', population: 67000000 },
13 ]);
14
15 React.useEffect(() => {
16 const timer = setInterval(() => {
17 if (order === ORDER.ASC) {
18 setItems(
19 items.sort(
20 (a, b) =>
21 parseFloat(a.population) - parseFloat(b.population)
22 )
23 );
24 setOrder(ORDER.DESC);
25 } else {
26 setItems(
27 items.sort(
28 (a, b) =>
29 parseFloat(b.population) - parseFloat(a.population)
30 )
31 );
32 setOrder(ORDER.ASC);
33 }
34 }, 3000);
35 return () => clearInterval(timer);
36 }, [order]);
37
38 return (
39 <>
40 {/* No Key */}
41
42 {/* Index key */}
43
44 {/* ID key */}
45 </>
46 );
47};

No key

1<div>
2 {items.map((item) => (
3 <input value={item.name} />
4 ))}
5</div>

That example we get Warning: Each child in a list should have a unique "key" prop.

Index key

1<div>
2 {items.map((item, index) => (
3 <input key={index} value={item.name} />
4 ))}
5</div>

That we don't see any warning in console, but let's compare that approach with the next example.

ID key

1<div>
2 {items.map((item, index) => (
3 <input key={item.id} value={item.name} />
4 ))}
5</div>

What is the difference?

In the first example you get the idea, it's required to set a key, but and the second and third examples, what is the problem?

Analyzing the code, we have a list with countries that will be reorder every 3000ms (ascending and descending), based of population.

Any time that we reorder component instances are updated and reused based on their key, if the key is an index, moving an item changes it. As a result, component state for things like uncontrolled inputs can get mixed up and updated in unexpected ways.

Keys should be stable, predictable, and unique. Unstable keys will cause many component instances and DOM nodes to be unnecessarily recreated, which can cause performance degradation and lost state in child components.

Here is an demo of reorder list with 3 approach above on CodePen.

To reproduce the issue described above, open the demo, and focus on first input of each section and wait for the reorder.


Thursday, June 27, 2024

Introduction of the useBem hook for React

Discover the power of the useBem hook to streamline your CSS class management, learn how to apply the BEM methodology to ensure consistent, readable, and maintainable styling across your front-end projects.


Wednesday, October 4, 2023

SOLID Principles in React

Let's explore how the SOLID principles can be applied to React components using TypeScript, functions, hooks, and interfaces.