← Back to home

The Key Prop in React

The key prop in React uniquely identifies elements within a list or dynamically rendered components. It ensures React can track which elements have changed, been added, or removed, allowing for efficient DOM updates.

Example:

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

import React from "react";
const Counter = () => {
  const [count, setCount] = React.useState(0);
  return (
    <div>
      <h1>{count}</h1>
      <button onClick={()=> setCount(count + 1)}>Increment</button>
      <button onClick={()=> setCount(count - 1)}>Decrement</button>
    </div>
  );
};

export default function Page() {
  const [milkOrTea, setShow] = React.useState(true);
  return (
    <div>
      <h1>Key Prop Demonstration</h1>
      <button onClick={()=> setShow(!milkOrTea)}>
        Toggle to {milkOrTea ? "tea" : "milk"}
      </button>
      {/* Switching between components with unique keys */}
      {milkOrTea ? <Counter key="milk" /> : <Counter key="tea" />}
    </div>
  );
}