React Key Prop

I am Frontend developer since 2022, mojorly use React as my frontend tool, but never go deep to understand what React key prop actually help.

But I got answer….

Since react uses Virtual Dom (V-DOM) in fiber architecture also in previous stack ones, it uses element position to determine the changes, for an example

here we see position of List and H1 under div block is changed, so react know create New JSX component, you can test this on this sandbox

https://codesandbox.io/p/sandbox/mv57gj - just remove key prop to see the effect.

So what’s happing here ?

React uses index of the list as default key but we are changing the position of the items so react is confuse so it is creating new instance every time for this.

What if we have same type of blocks ?

When you have same time of blocks and even they are derived by the props React will assume that they are the same component as before so internal state of thoes childs are preserved.

You can watch this video to get more clearity - https://www.youtube.com/watch?v=vXJkeZf-4-4&ab_channel=WebDevSimplified

So brother what is the advice ?

It’s good to use key prop while rendering block using any list iteration.

0
Subscribe to my newsletter

Read articles from Animesh Shrivatri directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Animesh Shrivatri
Animesh Shrivatri