REACT
React Key: Syntax, Usage, and Examples
React keys help identify elements in a list, allowing React to efficiently update the UI when elements change, add, or remove. Using unique keys improves performance by enabling React to track and re-render only the necessary parts of the DOM.
How to Use React Key
In React, keys are assigned to list items to help React recognize which elements have changed. The key should be a unique and stable identifier, typically an id
from your data.
Using Keys in a List
Each list item should have a unique key when rendering a dynamic list.
function UserList({ users }) {
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
In this example, React uses user.id
as the key to track each element.
Using Index as a Key
If your data lacks unique identifiers, you can use the index of the array. However, this is only advisable when the list is static and does not change dynamically.
function ItemList({ items }) {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
}
Using an index as a key can lead to UI inconsistencies when the list order changes.
When to Use React Key
Keys are essential in React when rendering dynamic lists. They help improve rendering efficiency and avoid unnecessary re-renders. Use keys in the following situations:
When Rendering a List of Components
Whenever you map over an array to generate JSX, each item needs a unique key.
function TaskList({ tasks }) {
return (
<div>
{tasks.map((task) => (
<p key={task.id}>{task.name}</p>
))}
</div>
);
}
When Conditionally Rendering Components
Keys help React distinguish between components that appear and disappear conditionally.
function Message({ notifications }) {
return (
<div>
{notifications.length > 0 ? (
<ul>
{notifications.map((note) => (
<li key={note.id}>{note.message}</li>
))}
</ul>
) : (
<p>No new notifications</p>
)}
</div>
);
}
When Using Keys in Animations
Keys allow React to identify elements during transitions and animations.
import { CSSTransition, TransitionGroup } from "react-transition-group";
function AnimatedList({ items }) {
return (
<TransitionGroup>
{items.map((item) => (
<CSSTransition key={item.id} timeout={300} classNames="fade">
<p>{item.text}</p>
</CSSTransition>
))}
</TransitionGroup>
);
}
Examples of React Keys
Using a Unique ID as a Key
If your data source provides unique IDs, use them as keys.
const products = [
{ id: "p1", name: "Laptop" },
{ id: "p2", name: "Phone" },
];
function ProductList() {
return (
<ul>
{products.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
);
}
When Should You Use Key in React for Components
Use keys whenever you generate a list dynamically in React. Without a key, React falls back to inefficiently identifying elements, which can lead to performance issues.
function UserCards({ users }) {
return (
<div>
{users.map((user) => (
<div key={user.id} className="card">
<h2>{user.name}</h2>
</div>
))}
</div>
);
}
React Key Prop in Dynamic Content
Keys help React determine if an element should be updated or re-created.
function RandomNumberList({ numbers }) {
return (
<ul>
{numbers.map((num) => (
<li key={num}>{num}</li>
))}
</ul>
);
}
If the same numbers appear multiple times, using the number itself as a key may not be ideal.
Using React Query Key
When working with React Query, keys help store and retrieve cached data efficiently.
import { useQuery } from "react-query";
function UserProfile({ userId }) {
const { data, error, isLoading } = useQuery(["user", userId], fetchUserData);
if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error loading user data.</p>;
return <h1>{data.name}</h1>;
}
The key ["user", userId]
ensures React Query correctly caches and retrieves user data.
Learn More About React Keys
Key in React
A key is a unique identifier that React uses to track elements in a list. Without a key, React may incorrectly match elements, causing unintended UI behavior.
function TodoList({ todos }) {
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.task}</li>
))}
</ul>
);
}
Handling Key Prop Warnings
If React displays a "key prop missing" warning, ensure each list item has a unique key.
function NumberList({ numbers }) {
return (
<ul>
{numbers.map((num) => (
<li key={num.toString()}>{num}</li>
))}
</ul>
);
}
Why Not to Use Index as a Key
Using an index as a key can cause React to misidentify elements if the list order changes.
function BadList({ items }) {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
}
If items are added or removed, React may fail to update the UI correctly.
React keys improve performance and prevent UI inconsistencies when rendering lists. Always use stable, unique identifiers like id
instead of array indexes to avoid unnecessary re-renders.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.