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.
key
is used to identify which items have 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 passed through a component to React'sVirtual DOM
, and it can't be destructed fromprops
to access its value.
Unique use cases of the key
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 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 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 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 theinput
'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" />]} />
If we won't pass the keys, we'll get the usual warning:
And, on top of that, we won't enjoy the optimization the key
provides us.
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)