Blog>
Snippets

React's Diffing Algorithm

Illustrate through examples how React's diffing algorithm works by comparing virtual DOM trees and updating the actual DOM selectively.
class List extends React.Component {
  render() {
    return (
      <ul>
        {this.props.items.map(item => <li key={item.id}>{item.text}</li>)}
      </ul>
    );
  }
}

// Assume our initial items are
const initialItems = [{ id: 1, text: 'Item 1' }, { id: 2, text: 'Item 2' }];

// Render the List with initial items
ReactDOM.render(<List items={initialItems} />, document.getElementById('root'));

// Update items list: remove the first item and add a new item
const updatedItems = [{ id: 2, text: 'Item 2' }, { id: 3, text: 'Item 3' }];

// Re-render the List with updated items
ReactDOM.render(<List items={updatedItems} />, document.getElementById('root'));
This example defines a React component called List that renders a list of items. Initially, it renders two items. Then it updates the items by removing the first item and adding a new one. React's diffing algorithm compares the two virtual DOM tree lists, identifies the changes, and updates the real DOM efficiently, removing the first item and inserting the third instead of re-rendering the entire list.