Q1. What are keys in React and why are they important?
Keys are special string attributes that help React identify which items in a list have changed.
They are important for performance and correct rendering, especially when lists are dynamic (adding, removing, reordering).
They are important for performance and correct rendering, especially when lists are dynamic (adding, removing, reordering).
Q2. Should you use the array index as a key?
Using index as key is acceptable only if the list is static and will not be reordered.
If the list can change, using indexes can cause issues like incorrect state mapping.
Prefer a unique identifier.
If the list can change, using indexes can cause issues like incorrect state mapping.
Prefer a unique identifier.
Q3. How do you choose a good key?
A good key is a stable, unique identifier from your data, such as a database ID or a UUID.
It should not change over time.
Avoid random numbers because they change on every render.
It should not change over time.
Avoid random numbers because they change on every render.
Q4. What is the scope of keys?
Keys only need to be unique among siblings in the same array.
They don't need to be globally unique.
Different arrays can have the same keys.
They don't need to be globally unique.
Different arrays can have the same keys.
Q5. Can you use keys on fragments?
Yes, you can use the
Use
<React.Fragment> syntax with keys, but the shorthand <> does not support keys.Use
<React.Fragment key={id}> if you need a keyed fragment.