Home  Reactjs   How react i ...

How react is better than traditional plain vanilla Javascript

Imagine an application that displays a large list of items, where users can filter and sort the list dynamically. This example will highlight the performance benefits of React's Virtual DOM when handling frequent and complex updates.

Direct DOM Manipulation

Managing the DOM manually in such a scenario can become cumbersome and inefficient, especially as the number of items grows. Here's a simplified example of how this might be handled:

<!DOCTYPE html>
<html>
  <body>
    <input type="text" id="filterInput" placeholder="Filter items..." oninput="filterItems()">
    <select id="sortSelect" onchange="sortItems()">
      <option value="asc">Ascending</option>
      <option value="desc">Descending</option>
    </select>
    <ul id="itemList"></ul>

    <script>
      const items = Array.from({ length: 1000 }, (_, i) => `Item ${i + 1}`);
      let filteredItems = [...items];

      function renderItems() {
        const itemList = document.getElementById('itemList');
        itemList.innerHTML = '';
        filteredItems.forEach(item => {
          const li = document.createElement('li');
          li.textContent = item;
          itemList.appendChild(li);
        });
      }

      function filterItems() {
        const filterValue = document.getElementById('filterInput').value.toLowerCase();
        filteredItems = items.filter(item => item.toLowerCase().includes(filterValue));
        renderItems();
      }

      function sortItems() {
        const sortValue = document.getElementById('sortSelect').value;
        filteredItems.sort((a, b) => sortValue === 'asc' ? a.localeCompare(b) : b.localeCompare(a));
        renderItems();
      }

      renderItems();
    </script>
  </body>
</html>

React with Virtual DOM

In React, the same functionality can be implemented more efficiently and with better performance, especially as the application grows in complexity:

import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';

function App() {
  const [items] = useState(Array.from({ length: 1000 }, (_, i) => `Item ${i + 1}`));
  const [filteredItems, setFilteredItems] = useState(items);
  const [filter, setFilter] = useState('');
  const [sortOrder, setSortOrder] = useState('asc');

  useEffect(() => {
    let newItems = items.filter(item => item.toLowerCase().includes(filter.toLowerCase()));
    newItems = newItems.sort((a, b) => sortOrder === 'asc' ? a.localeCompare(b) : b.localeCompare(a));
    setFilteredItems(newItems);
  }, [filter, sortOrder, items]);

  return (
    <div>
      <input
        type="text"
        placeholder="Filter items..."
        value={filter}
        onChange={e => setFilter(e.target.value)}
      />
      <select value={sortOrder} onChange={e => setSortOrder(e.target.value)}>
        <option value="asc">Ascending</option>
        <option value="desc">Descending</option>
      </select>
      <ul>
        {filteredItems.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById('app'));

Performance Benefits of React and Virtual DOM

  1. Efficient Updates:

    • React only updates the parts of the DOM that have changed. In the direct DOM manipulation example, every time the list is filtered or sorted, the entire list is re-rendered. React, on the other hand, performs a diffing algorithm to update only the necessary elements.
  2. Declarative Approach:

    • React's declarative nature makes it easier to reason about the state and UI changes. You describe what the UI should look like based on the current state, and React handles the rendering.
  3. Component-Based Architecture:

    • React promotes a component-based architecture, which improves code maintainability and reusability. In the direct DOM manipulation example, you need to manually handle the DOM updates, which can become error-prone as the application grows.
  4. State Management:

    • React's state management and lifecycle methods make it easier to manage and synchronize state changes. This is particularly useful in complex applications with multiple interdependent states.
Published on: Jul 04, 2024, 07:06 AM  
 

Comments

Add your comment