
Skip to the unique use cases ofkey
🦅
What is thekey
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.
key
is used to identify which itemshave changed, are added, or are removed.key
only makes sense in the context of the surrounding array.key
is astring
ornumber
. The best way to pick a key is to use astring
that uniquely identifies a list item among its siblings.Most often you would use IDs from your data as keys.key
is passedthrough a component to React'sVirtual DOM
, and it can't be destructed fromprops
to access its value.
Unique use cases of thekey
prop
◈ Avoid UI flicker
UI flicker - With 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 theStack
component).
It happens because we're using aReact.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 adiv
, for example, we will only have one child and thegap="20px"
prop won't apply.
In this case, it is a styling preference to wrap it withReact.Fragment
.
◈ Mount a new component instance (by@davidkpiano)
Rather than anonChange
event, wecouple the state to theinput
using thekey
prop.
With every state change, we mount a new component instance of theinput
.
try commenting-out the
key
prop and see that theinput
's value doesn't change.
◈ Manually addkey
to everyReact 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 uniquekey
to each node.
<Mainactions={[<PlusCharkey="plus-char"/>,<MinusCharkey="minus-char"/>]}/>
If we won't pass the keys, we'll get the usual warning:
And, on top of that, we won't enjoy the optimization thekey
provides us.
Conclusion:
The lack of akey
can cause more than just a warning.
It can cause a UI flicker, or forcefully mount a new component instance.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse