VITSOLS
2025-11-09
Why Use Lists in React?
Lists are used to display repeated content dynamically. Instead of writing multiple elements manually, React allows you to map over an array and render components for each item — making the UI more scalable and maintainable.
Basic Example – Rendering a List
The ternary operator is widely used for short inline conditional rendering. It helps simplify conditions directly within the JSX.
function NameList() {
const names = ['Vara', 'Prasad', 'Suravarapu'];
return (
<ul>
{names.map((name) => (
<li>{name}</li>
))}
</ul>
);
}
export default NameList;
The above example loops through the names array and renders a list item for each entry. But wait—React will warn you about a missing key prop.
What Are Keys and Why Are They Important?
Keys help React identify which items have changed, been added, or removed. They improve performance and prevent unexpected UI behavior during re-renders.
Adding Keys to List Items
You can use helper functions to simplify conditional rendering when logic becomes complex.
function NameList() {
const names = ['Vara', 'Prasad', 'Suravarapu'];
return (
<ul>
{names.map((name, index) => (
<li key={index}>{name}</li>
))}
</ul>
);
}
In this example, we used the array index as a key. While it works in simple cases, it’s better to use a unique identifier from your data (like an ID) to ensure React updates items accurately.
Rendering Lists from Objects
function ProductList() {
const products = [
{ id: 1, name: 'Laptop' },
{ id: 2, name: 'Smartphone' },
{ id: 3, name: 'Tablet' }
];
return (
<ul>
{products.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
);
}
Real-Time Use Case
In real-world applications, you might fetch data from an API (like a product list, user comments, or messages). You can then use map() to render each item dynamically.
function UserList({ users }) {
return (
<div>
<h3>Registered Users</h3>
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
}
Best Practices
- Always assign a unique
keywhen rendering lists. - Avoid using array indexes as keys for dynamic data.
- Use stable and unique identifiers such as database IDs.
- Keep lists small and efficiently rendered for performance.
How These Are Helpful in Real-Time
In real-time scenarios like chat apps, data dashboards, and notification panels, React efficiently updates only the changed items instead of re-rendering the entire list. This improves performance and provides a smooth user experience.