React — The hidden function for keys

You know you should pass keys for lists so React doesn’t get mad at you right?
So you think: why not just key everything? Better yet… why not make it random?
Keys!
Outside of lists that you map, you might think keys have no function, after all, most, if not all, tutorials only mention keys in the context of mapping a list right?
If you’re like me, you probably only key lists, maybe you forget sometimes, see the warning, and add the key.
But some people go in the other direction and start using key everywhere! Sometimes using something random like Math.random() or new Date().getTime().
You might think: “Weird, but okay…”, except no! it’s not okay and you might end up with a bug impossible to debug (unless you go down the hole of debugging the actual React code).
Things to know about the keys
You can have the SAME key, as long as they are on different levels (even in the same component!)
function ThisIsOk(){
return (
<div key="this is ok!">
<AnyComponent key="this is ok!" />
<div> {/* here wouldn't be ok */}
<AnotherComponent key="this is ok!" />
</div>
</div>
)
}This happens because, well… trees!
If you see how React renders things, you know it’s basically one big tree of components (also, that’s why you can’t have a component returning multiple components without a wrapper).
React picks all components and makes a list of them, and when you put a key on them, a few things will happen:
- React doesn’t need to “add a key to it” (or whatever it does internally)
- React will treat any component with that key as the same component!
- React will easily remove components if it doesn’t find the key again.
Examples:
Here is a little sandbox, try to use the inputs… if you can.
https://codesandbox.io/s/keys-example-ll5rxg?file=/src/App.js




