In React, the key
attribute is a special attribute that’s primarily used to optimize the performance of rendering lists of components or elements. The key
attribute identifies each component or element in the list. It should be a unique identifier within the list. React uses the key
to keep track of which components or elements have changed, been added, or been removed.
The key attribute is a special attribute and is not included in the props object passed to the component.
An example of how the key attribute is used in a list of elements
function Component() {
const items = ["Item 1", "Item 2", "Item 3"];
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
}
How to reset a component
The developer can reset a component by changing its key
prop. When the key
of a component changes, React treats it as a completely new component instance and re-renders it from scratch. This can effectively reset the component’s state and any internal stateful logic.
An example of how to reset a component by changing its key prop
Parent.tsx
import { useState } from "react";
import Child from "./Child";
export default function Parent() {
const [count, setCount] = useState<number>(0);
const [reset, setReset] = useState<number>(0);
return (
<div>
<h2>Parent</h2>
<button
onClick={() => {
setCount((prev) => ++prev);
}}
>
Increase
</button>
<span>{count}</span>
<button
onClick={() => {
setReset((prev) => ++prev);
}}
>
Reset Child
</button>
<span>{reset}</span>
<hr />
<Child key={reset} />
</div>
);
}
Child.tsx
import { useState } from "react";
export default function Child() {
const [count, setCount] = useState<number>(0);
return (
<section>
<h2>Child</h2>
<button
onClick={() => {
setCount((prev) => ++prev);
}}
>
Increase
</button>
<span>{count}</span>
</section>
);
}
When the “Reset Child” button is clicked, the setReset() generates a new unique key. This new key is then passed as the key
prop to the Child component, causing it to re-mount and reset its state.