Dan Profile picture
14 Jul, 14 tweets, 5 min read
Why React Needs Keys, a short visual explanation.

Each render is like a frame in a movie. React doesn’t know *what* you did with your data. It only sees the JSX from the previous render and then from the next render.

circles.map(c => <Circle color={c.color} />) Two frames. First has red, yellow, blue colors. Second has r
Tell me what happened to circles. If you look close enough, you’ll realize there are two *different* possible interpretations of what happened!

1. Maybe second and third circles swapped positions…

2. Or maybe the second circle became blue and the first circle became yellow! Illustration of them swapping positionsIllustration of them changing colors
Normally this wouldn’t matter. But imagine each circle has state inside. Like a checkbox or an input. Then the difference between “moving” and “changing” becomes significant! In the first case you *want* the state to move too. In the second case you don’t.
So what are keys? Keys are a hint you give to React so that it knows how to know which of the two cases it is.

circles.map(c => <Circle color={circle.id} />)

It’s a way to tell React “what makes two circles the *same* circle, even between renders”. Circles with keys abc become circles with keys acbCircles with keys abc become circles with keys abc
React can’t make up a good key itself. Only *you* know how your data is structured and whether two circles in two renders are “the same” circle conceptually (even if all of its data changed) or not. Usually you’d use an ID generated during data creation. Such as from a database.
If you don’t specify a key in a list, React will fall back to using an index. And of course you could also pass index as a key yourself.

It’s not necessarily “wrong” or “slow” or anything like this. It’s just that you’re telling React “I promise the circles never change order.” Circles indexed as 1, 2, 3, corresponding to circles indexed
What happens if you pass a random key every time? Well, you’re telling React that circles are *never* the same between renders. So if you have some state inside of them, it will be lost after every re-render. React will destroy and recreate every circle because you told it to. Circles always getting recreated
And that’s the principle behind keys! They’re not something that React can guess or automate for you because you’re the only person who knows whether you meant “these items were moved/inserted/removed” or “these items changed their content”. Nobody else knows that.
Why doesn’t React “guess” what happened from what I did to my array? First, from React’s perspective, your array is completely different every time—a new copy.

But even if React *did* track your changes it wouldn’t be enough! Refetching data would give you new arrays anyway.
Keys are for more than just arrays. They specify a component’s identity — is this the “same” or “different” component between re-renders. You can use this to reset state:

<ChatThread key={contact.id} />

This makes switching the contact reset all text fields inside.
In the long term, when React gets built-in deep support for Animations, keys will play a big role there too. Think about it: the difference between “moving/adding/deleting” and “updating” becomes obviously visual! If things animate in and out as you didn’t intend, the key is bad.
And that’s it for today 🙂 we’ll definitely add something along the lines of this explanation to the new docs.
*Correction this should’ve said

circles.map(c => <Circle color={c.color} key={c.id} />)

I haven’t fully woken up.

• • •

Missing some Tweet in this thread? You can try to force a refresh
 

Keep Current with Dan

Dan Profile picture

Stay in touch and get notified when new unrolls are available from this author!

Read all threads

This Thread may be Removed Anytime!

PDF

Twitter may remove this content at anytime! Save it as PDF for later use!

Try unrolling a thread yourself!

how to unroll video
  1. Follow @ThreadReaderApp to mention us!

  2. From a Twitter thread mention us with a keyword "unroll"
@threadreaderapp unroll

Practice here first or read more on our help page!

More from @dan_abramov

12 Jun
It's another Friday night indoors, so being the nerd I am, of course I am playing with adding startTransition to open source apps to see if it works. Don't judge me
We really need to make some demos but maybe I could record a few short videos if y'all are curious (but no FOMO please, it's still an Alpha, etc)
Okay so this one shouldn't be hard to follow. There's an input and a table. Currently, table state update is delayed and debounced so it doesn't stutter typing. But stutter is noticeable if I type slower. (Caveat: we're in DEV mode so the real app is faster—but nice for demo.)
Read 29 tweets
10 Jun
@DavidKPiano @acemarke @modernserf I’ve tried to be more precise with my wording here—does this help? I didn’t see my tweet as a criticism but maybe I have misread the room.
@DavidKPiano @acemarke @modernserf My point is that, I don’t agree with the premise of rejecting tools based on them being complex inside. Requirements of modern client apps are complex! So that complexity has to live somewhere. I know doesn’t live inside Redux because I literally wrote it. I can’t say this?
@DavidKPiano @acemarke @modernserf This complexity could live in application code, it could live in a meta-library on top of Redux, or somewhere else. I just definitely know that it’s not in those 100 lines of code. And that’s okay. It’s not a criticism. It is a direct reflection of what Redux is (and isn’t).
Read 4 tweets
10 Jun
Love this thread. Someday I’d like to write (or contribute to) a five year retrospective of this project. So many stories! For now I’ll do a small thread of random fun moments I remember from the last couple of years.
When we started, we wrote our own scheduler with a plan that eventually the browser would provide a native one. Our work on React took long enough that by this year, the native scheduler already exists behind a flag and we could even experiment with it! chromestatus.com/feature/603116…
Our first thinking about how Suspense should work didn’t make sense. We found out the hard way in the middle of the FB website rewrite in 2019. A simple change could make UI stall for 5 seconds and engineers couldn’t say why. We couldn’t either. We were confused by our own API!
Read 32 tweets
11 Apr
Looking for a very particular kind of *instrumental* music. Needs to be a bit non-idiomatic, kaleidoscopic in texture. But with beautiful ethereal moments of harmony when things come together. Some of Four Tet, Boards of Canada, Bibio stuff is like this. Give me more.
References Bibio — YouBoards of Canada — Dayvan CowboyFour Tet — Angel EchoesMaribou State — Feel Good
Would be cool if went into a more math rock direction but still beautiful, not just technical
Read 5 tweets
10 Apr
What are your favorite songs in 3/4? (Meaning waltz type beat: one-two-three, one-two-three...) Spotify or YouTube links pls.
Tom Waits — Widow’s Grove. No idea what it’s about but so pretty. I think the music itself sounds like a riff on some traditional folk melody but don’t know the lineage.
БГ — Елизавета. This one is in Russian. It gives me a similar feeling as Widow’s Grove that despite the lyrics being abstract and obscure, I feel exactly what it says.
Read 13 tweets
23 Mar
I’ve lived 80% of my life in Russia and 20% in the UK. Both countries have some strange or unpleasant aspects. (For example, one of them poisons its own citizens with a nerve agent.)

Neither of them has news reports every other week about some random person shooting up a store.
The most fascinating to me is that while there seems to be majority support for stricter laws, there’s also majority opposition to e.g. outright banning handguns. I’m perplexed as to what kind of experiences one needs to have to be convinced that weapons with bullets are needed.
I know some people say guns are their hobby. My thinking process is, like, maybe you could pick a different hobby? How about making bombs, is that a reasonable hobby too?

Though a designated park where people who like to shoot can hang out with each other seems like an OK idea.
Read 18 tweets

Did Thread Reader help you today?

Support us! We are indie developers!


This site is made by just two indie developers on a laptop doing marketing, support and development! Read more about the story.

Become a Premium Member ($3/month or $30/year) and get exclusive features!

Become Premium

Too expensive? Make a small donation by buying us coffee ($5) or help with server cost ($10)

Donate via Paypal Become our Patreon

Thank you for your support!

Follow Us on Twitter!

:(