How does react key works

116 Views Asked by At

I read this article about 'why using index as a key is an anti pattern' and got curious why my project works so well with index based key matrix.

I worked on tetris project, and every second, matrix with 20 * 24 cells re-render and move tetromino. Each cell of the array includes the alphabet and it becomes division's className and decide the color of the cell and every second when tetromino moves, it works very well.

From his article's example and this question, if key doesn't get changed, react doesn't change that DOM element and add new DOM for a new item in the array. So my tetris stage should not update view because key doesn't get changed. I got so confused how react key works.

I searched a lot of articles, but what I could find only was that they are using for optimization and compare DOM, but not how. So I want to know, how does key works and what kind of procedure they do to compare before change Virtual Dom and after change Virtual DOM

2

There are 2 best solutions below

0
On BEST ANSWER

React on its own when not using 'key' attribute is not very efficient when comparing lists, if an item at the beginning of the list is changed or inserted.

If you insert an element at the beginning of your list, React will rerender the whole list and not just add the inserted item (if you have no key attribute set). Same applies if you use an index based key, as the key of all items will change on insertion and therefore the whole list will rerender.

With a correctly set key attribute react is able detect which item was inserted or changed and only rerender this part of the list. You can find a detailed example and explanation in the React Docs in Recursing On Children and Keys.

You can inspect this effect if you use the browser extension "React Dev Tools". With the extension active, you can do the following:

  1. open browser developer tools
  2. got to "Component"-tab
  3. go to tab settings (gear icon)
  4. toggle "Highlight updates when components render."
  5. try to insert an item of the beginning of a list with no key, and then again with a list which uses unique keys, an check which Components update

Using an index based key will work just fine, however performance wise it is not very efficient in cases where the dynamic list is updated at lower indices.

0
On

Key is like the id of the item, it's a bad practice to use indexes because if one of the items change his position in the list all the list will rerender, you probably can find cases that it will not affect your performance so much but I think it's a bad habit.

check this out: Why Are Keys Important In React