logo
Back to blogs

Understanding React Keys and Their Importance

Mar 10, 2023 - 5 min read

Understanding React Keys and Their Importance

Why are Keys Important?

Let’s consider a React application with two counters (e.g., for milk and tea) Switching between them demonstrates why key is essential.

KeyPropDemonstration.tsx
1import React from "react"; 2const Counter = () => { 3 const [count, setCount] = React.useState(0); 4 return ( 5 <div> 6 <h1>{count}</h1> 7 <button onClick={()=> setCount(count + 1)}>Increment</button> 8 <button onClick={()=> setCount(count - 1)}>Decrement</button> 9 </div> 10 ); 11}; 12 13export default function Page() { 14 const [milkOrTea, setShow] = React.useState(true); 15 return ( 16 <div> 17 <h1>Key Prop Demonstration</h1> 18 <button onClick={()=> setShow(!milkOrTea)}> 19 Toggle to {milkOrTea ? "tea" : "milk"} 20 </button> 21 {/* Switching between components with unique keys */} 22 {milkOrTea ? <Counter key="milk" /> : <Counter key="tea" />} 23 </div> 24 ); 25}