DEV Community

Cover image for React Key - Not Only In map
Daniel Bellmas
Daniel Bellmas

Posted on

React Key - Not Only In map

Skip to the unique use cases of key πŸ¦…

What is the key prop? πŸ—

The key prop is all about optimization.
Setting key will inform React of which specific items have changed and need to be re-rendered. This is important for performance reasons, as React will only re-render the items that have changed, instead of the entire list.

  1. key is used to identify which items have changed, are added, or are removed.

  2. key only makes sense in the context of the surrounding array.

  3. key is a string or number. The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys.

  4. key is passed through a component to React's Virtual DOM, and it can't be destructed from props to access its value.


Unique use cases of the key prop

β—ˆ Avoid UI flicker

UI flicker - With a key

UI flicker - With a key

UI flicker - Without a key

UI flicker - Without a key

The difference is subtle but we can see that the blue background lingers for a bit after pressing the first button (which changes the children of the Stack component).

It happens because we're using a React.Fragment to wrap the children. If we were to use a div or some other wrapping tag, then we won't see the flicker.

So why not just do that instead you ask?
By wrapping with a div, for example, we will only have one child and the gap="20px" prop won't apply.
In this case, it is a styling preference to wrap it with React.Fragment.


β—ˆ Mount a new component instance (by @davidkpiano)

Rather than an onChange event, we couple the state to the input using the key prop.
With every state change, we mount a new component instance of the input.

try commenting-out the key prop and see that the input's value doesn't change.


β—ˆ Manually add key to every React Node in an array

Although it is not that unique, it can easily be ignored since there is no map here.
When passing a prop that is an array of react nodes (react components) we need to add a unique key to each node.



<Main actions={[<PlusChar key="plus-char" />, <MinusChar key="minus-char" />]} />


Enter fullscreen mode Exit fullscreen mode

If we won't pass the keys, we'll get the usual warning:
Key warning

And, on top of that, we won't enjoy the optimization the key provides us.

Everybody gets a key meme

Conclusion:

The lack of a key can cause more than just a warning.
It can cause a UI flicker, or forcefully mount a new component instance.

Top comments (0)