Interview question
How do you render lists in React? Why are keys important? React में lists कैसे render करते हैं? Keys क्यों महत्वपूर्ण हैं?
Answer
// Rendering lists with map()
function ItemList({ items }) {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item.name}</li>
))}
</ul>
);
}
// Best practice: Use unique ID as key
function UserList({ users }) {
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
// Rendering nested lists
function TodoApp({ todos }) {
return (
<div>
{todos.map(todo => (
<div key={todo.id}>
<h3>{todo.title}</h3>
<ul>
{todo.items.map(item => (
<li key={item.id}>{item.text}</li>
))}
</ul>
</div>
))}
</div>
);
}
// Why keys are important:
// 1. Help React identify which items have changed
// 2. Preserve component state in dynamic lists
// 3. Prevent bugs in forms and inputs
// 4. Improve performance
// BAD: Using index as key (can cause bugs)
function BadList({ items }) {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li> // DON'T DO THIS
))}
</ul>
);
}
// GOOD: Using unique identifier
function GoodList({ items }) {
return (
<ul>
{items.map(item => (
<li key={item.id}>{item.name}</li> // Use unique ID
))}
</ul>
);
}
// Real-world example with state
function TodoList() {
const [todos, setTodos] = useState([
{ id: 1, text: 'Learn React' },
{ id: 2, text: 'Build projects' }
]);
const addTodo = () => {
const newTodo = { id: Date.now(), text: 'New todo' };
setTodos([...todos, newTodo]);
}
return (
<div>
<button onClick={addTodo}>Add Todo</button>
<ul>
{todos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
</div>
);
}
// Fragment for rendering multiple elements
function List({ items }) {
return (
<>
{items.map(item => (
<React.Fragment key={item.id}>
<dt>{item.term}</dt>
<dd>{item.description}</dd>
</React.Fragment>
))}
</>
);
}Lists render करना:
map() से render करते हैं:
items.map(item => <li key={item.id}>{item.name}</li>)
Keys का महत्व:
1. React को identify करने में help
2. List में items के state को preserve करता है
3. Forms में bugs prevent करता है
4. Performance improve करता है
Best practices:
- Always use unique ID as key
- Index को key न बनाएं (items add/remove से bugs)
- Key फिर से generate न करेंWas this answer clear?