React list and keys

Created By: chatGPT

In React, rendering lists of data is a common task. Each item in the list needs to be uniquely identified for efficient updates and rendering. This is accomplished using keys.
const items = ['Apple', 'Banana', 'Cherry'];

const ItemList = () => {
    return (
        <ul>
            {items.map((item, index) => (
                <li key={index}>{item}</li>
            ))}
        </ul>
    );
};
It's important to use a stable identifier as a key when available, rather than relying on the index. This helps React optimize performance by minimizing the number of updates needed when the list changes.
const TodoList = ({ todos }) => {
    return (
        <ul>
            {todos.map(todo => (
                <li key={todo.id}>{todo.text}</li>
            ))}
        </ul>
    );
};
If we use the index as a key, it can lead to issues when the list items reorder or are added/removed. React may not preserve the element state correctly.
const items = ['Apple', 'Banana', 'Cherry'];

const ItemList = () => {
    return (
        <ul>
            {items.map((item, index) => (
                <li key={index}>{item}</li>
            ))}
        </ul>
    );
};
When updating a list, make sure your keys are consistent from one render to the next. If the keys change, React may treat the items as new elements, which can lead to performance issues and bugs.
const itemsWithId = [{ id: 1, text: 'Apple' }, { id: 2, text: 'Banana' }, { id: 3, text: 'Cherry' }];

const ItemList = () => {
    return (
        <ul>
            {itemsWithId.map(item => (
                <li key={item.id}>{item.text}</li>
            ))}
        </ul>
    );
};
Introduction And SetupComponentsPropsStateLifecycle MethodsHooksContext APIJsx SyntaxVirtual DomEvent HandlingFormsRoutingPerformance OptimizationError BoundariesHigher Order ComponentsRender PropsPortalsFragmentsRefsControlled ComponentsUncontrolled ComponentsMemoizationSuspenseLazy LoadingProp TypesDefault PropsConditional RenderingList And KeysAccessibility (a11y)State ManagementTestingCustom HooksUseEffectUseStateUseContextUseReducerUseMemoUseCallbackUseRefUseLayoutEffectUseImperativeHandleUseDebugValueAutomatic BatchingSuspense For Data FetchingStrict ModeForward RefsCreateContextLazyUseTransitionUseDeferredValueUseId