React-Why is ‘key’ is necessary

JSCCC
2 min readApr 11, 2021

Why do I need Keys in React Lists?

There can be thousands of lists in an app and It could take a toll on the application’s performance. To optimize and improve performance aspect, React uses an unique key to identify which item has changed-modify, add, remove.
You should assign an unique key for each item instead of using an index as a key because an index can be changed as you add/remove elements. When you use index as a key and add a new element into an array, old index is used when you render. It creates unwanted behavior.
It’s not recommend to use an index instead of generating an unique id for each item, but you can still use an index only when you know for sure that your list is static and will never change.
Keys should be only unique inside of the array. It doesn’t have to be globally unique, which means you can use same id key for other components and arrays.
Key shouldn’t be generated ramdomly.

How to use “useState”

import { useState } from ‘react’const [value, setValue] = useState([
//content of value-objects in an array
{
id: 1,
text: "This is the first text"
}])
//to add a new object
setValue([...values, {id:2, text: "This is the second"}]);

When you define a props at the top level, you can access this within other components only from parent to child. It’s read only.

Props! — and how to pass props to components in React . (part_1)

--

--