Interview question
What are keys and why are they important in rendering lists? Keys क्या हैं और lists render करते समय क्यों महत्वपूर्ण हैं?
Answer
// GOOD - using unique ID
function TodoList({ todos }) {
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}
// BAD - using index (can cause bugs)
function TodoList({ todos }) {
return (
<ul>
{todos.map((todo, index) => (
<li key={index}>{todo.text}</li>
))}
</ul>
);
}
// Why keys matter:
// 1. Help React identify changed items
// 2. Preserve component state
// 3. Maintain form input values
// 4. Avoid UI bugs when reorderingKeys का महत्व:
1. React को identify करने में help
2. State preserve करता है
3. Form values maintain करता है
4. Always use unique IDs, not indexWas this answer clear?