← react hacks / react / rendering-lists-with-keys.md

Rendering Lists with Keys in React

Learn how to efficiently render lists in React using keys. This hack covers the importance of keys and how to use them in your React applications.

In React, lists can be rendered by mapping through an array of data and returning JSX for each item. However, to ensure each item in the list is uniquely identified, React requires a key prop.

const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
  <li key={number.toString()}>
    {number}
  </li>
);

The key is a special string attribute you need to include when creating lists of elements. Keys help React identify which items have changed, are added, or are removed.

However, do not use indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with the component state.

const todoItems = todos.map((todo, index) =>
  // Only do this if items have no stable IDs
  <li key={index}>
    {todo.text}
  </li>
);

Instead, it’s better to use unique string identifiers from your data if available.

Understanding and properly implementing keys in React will lead to better performance and fewer bugs in your application.

Keep experimenting!

Quick hacks and tips from my daily workflow. Found this useful? Let me know.

@samuellawrentz →

$ ls ../react | head -4

More hacks

cd ../react →
  1. c52b973 Harnessing the Power of useRef Hook in React

    tag: reacttag: hookstag: useRef

  2. 8150376 Adding Event Handlers in JSX

    tag: reacttag: jsxtag: event handlers

  3. 2c098c3 Avoiding Unnecessary Re-renders with React.memo

    tag: reacttag: web developmenttag: performance optimization

  4. c2ffa3b Optimizing React Apps with useCallback

    tag: reacttag: useCallbacktag: optimization

00:00

This helps me increase the session time of my site. Thank you!

Can you stay a bit longer?