Blog>
Snippets

Keys in Reconciliation

Use a list of items rendered in React with and without keys, and demonstrate the difference in how React reconciles the components.
class WithoutKeys extends React.Component {
  constructor(props) {
    super(props);
    this.state = { items: ['Item 1', 'Item 2', 'Item 3'] };
  }

  shuffleItems = () => {
    this.setState(prevState => ({
      items: prevState.items.sort(() => 0.5 - Math.random())
    }));
  };

  render() {
    return (
      <div>
        <button onClick={this.shuffleItems}>Shuffle Items</button>
        <ul>
          {this.state.items.map(item => (
            // No key provided here, React cannot track items efficiently
            <li>{item}</li>
          ))}
        </ul>
      </div>
    );
  }
}
This example shows a React component that renders a list of items without using keys. When items are shuffled, React does a poor job at reconciling them because it can't track which items have changed.
class WithKeys extends React.Component {
  constructor(props) {
    super(props);
    this.state = { items: ['Item 1', 'Item 2', 'Item 3'].map((item, index) => ({id: index, value: item})) };
  }

  shuffleItems = () => {
    this.setState(prevState => ({
      items: prevState.items.sort(() => 0.5 - Math.random())
    }));
  };

  render() {
    return (
      <div>
        <button onClick={this.shuffleItems}>Shuffle Items</button>
        <ul>
          {this.state.items.map(item => (
            // Providing a unique key for each item for efficient tracking and reconciliation
            <li key={item.id}>{item.value}</li>
          ))}
        </ul>
      </div>
    );
  }
}
This example shows a React component that renders a list of items with keys. Each item is an object with a unique 'id' property used as a key when rendering. Thanks to keys, React reconciles the components efficiently when items are shuffled.