avatarBruno Noriller

Summary

The provided web content discusses the importance and nuances of using keys in React to maintain component identity and state, cautioning against using random keys and explaining that the same key can be used on different levels, which can affect component lifecycle and behavior.

Abstract

React developers are familiar with the necessity of assigning keys to elements within a list to prevent console warnings. However, the use of keys extends beyond just lists. The article explains that keys in React serve a crucial role in component reconciliation and state persistence. While some developers may overuse keys, assigning them randomly to components, this practice can lead to unpredictable behavior and debugging headaches. Properly utilized, keys help React identify which components have changed, been added, or been removed. The same key can be used across different levels in the component tree without issue, but it must be unique at the same level. Misusing keys by making them random can result in components being destroyed and recreated unnecessarily, causing performance issues and state loss. The article also highlights that understanding keys can prevent common bugs where components refuse to reset, offering a solution by changing the component's key to signal React that it's a new component. This insight can lead to more efficient use of React's state management without relying on useEffect for state resets.

Opinions

  • The article suggests that using random keys is a common misconception and a practice to be avoided, emphasizing that this can introduce bugs that are difficult to trace.
  • The author points out that React's reconciliation process is tree-based, and keys are used to track components in this tree, which is why the same key can be used at different levels without conflict.
  • The author shares a personal anecdote, indicating that they, like many others, have experienced the frustration of components not resetting properly, and offers the use of keys as a solution to manage component state more effectively.
  • There is a subtle implication that some developers might not fully understand the implications of keys beyond their use in lists, as most tutorials only cover keys in that context.
  • The author provides a practical example using a sandbox environment to demonstrate the impact of keys on component behavior, which serves as a hands-on learning tool for the reader.
  • Lastly, the article promotes an AI service called ZAI.chat as a cost-effective alternative to ChatGPT Plus (GPT-4), suggesting that understanding React's behavior with keys is a valuable skill for developers.

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

What’s happening there is that the components with something random are being destroyed on each render because every time the component needs to re-render it finds a different key. Be it directly or indirectly.

Then you have the ones without keys or with a static key. Also the one with the same key but on different levels.

Finally the weird one: two components with the same key but alternating which one is being rendered. Since it’s the same key, same place, you’re basically saying it’s the same component and the state persists!

What does this mean?

You’ve probably encountered a bug where you couldn’t make a component reset no matter what, so you started using useEffect with some dependency to reset the state… well, you’re not alone!

But now… you know why and you also know that you just need to pass it a different key to reset the state… no useEffect needed!

You also know that you can render the same component in the same place and it retains the state it had. Although I’m not sure where to leverage this. Even that example… usually we would just bring whatever it needs to make the if works inside.

Cover Photo by Samantha Lam on Unsplash

JavaScript
Typescript
React
Web Development
Programming
Recommended from ReadMedium