Comparing React VS HTMX: Choosing the Right Frontend Approach
Tags: react, htmx, node, express
Published: 2023-06-23 03:53:31

## Introduction:

Building modern web applications often requires combining a robust backend framework with a frontend framework to create dynamic and interactive user experiences. React and HTMX are two popular choices when it comes to frontend development. In this article, we'll explore the differences between React and HTMX, and how they can be used to create compelling web applications. We'll also provide practical examples for each approach.

## React:

React has gained significant popularity in the web development community due to its component-based architecture and efficient rendering capabilities.

Using React involves setting up frontend environment powered by tools like Webpack. React components can then be used to fetch data from the backend through APIs and render it dynamically on the client-side. This approach provides a seamless user experience, as React updates only the necessary parts of the UI, avoiding full page reloads.

## React Example App:

This example actively searches a contacts database as the user enters text.

We start with a search input and an empty table:

```jsx
import React, { useState } from 'react';

function ContactSearch() {
  const [searchResults, setSearchResults] = useState([]);

  const handleSearch = (event) => {
    const searchTerm = event.target.value;

    fetch('/search', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ search: searchTerm }),
    })
      .then((response) => response.json())
      .then((data) => {
        setSearchResults(data);
      });
  };

  return (
    <div>
      <h3>
        Search Contacts
        <span className="htmx-indicator">
          <img src="/img/bars.svg" alt="Loading..." /> Searching...
        </span>
      </h3>
      <input
        className="form-control"
        type="search"
        name="search"
        placeholder="Begin Typing To Search Users..."
        onChange={handleSearch}
      />
      <table className="table">
        <thead>
          <tr>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Email</th>
          </tr>
        </thead>
        <tbody id="search-results">
          {searchResults.map((contact) => (
            <tr key={contact.id}>
              <td>{contact.firstName}</td>
              <td>{contact.lastName}</td>
              <td>{contact.email}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

export default ContactSearch;
```

## Express.js app for React frontend

```js
const express = require('express');
const app = express();

// POST /search route
app.post('/search', (req, res) => {
  // Simulating search logic
  const searchTerm = req.body.search;
  const searchResults = [
    { id: 1, firstName: 'John', lastName: 'Doe', email: 'john@example.com' },
    { id: 2, firstName: 'Jane', lastName: 'Doe', email: 'jane@example.com' },
  ];

  // Filter the search results based on the searchTerm
  const filteredResults = searchResults.filter((result) => {
    const firstNameMatch = result.firstName.toLowerCase().includes(searchTerm.toLowerCase());
    const lastNameMatch = result.lastName.toLowerCase().includes(searchTerm.toLowerCase());
    const emailMatch = result.email.toLowerCase().includes(searchTerm.toLowerCase());

    return firstNameMatch || lastNameMatch || emailMatch;
  });

  // Simulating delay for illustration purposes
  setTimeout(() => {
    res.json(filteredResults);
  }, 1000); // Delayed response for 1 second
});

// Start the server
app.listen(3000, () => {
  console.log('Server started on port 3000');
});
```

## HTMX:

HTMX takes a different approach by focusing on enhancing the user interface with minimal JavaScript code. HTMX allows you to add interactivity to your frontend using declarative attributes embedded directly in your HTML markup.

With HTMX we leverage the power to update individual task items without reloading the entire page. HTMX achieves this by making HTTP requests to the server in the background and updating specific elements on the page using the hx-swap attribute. This approach simplifies the development process by reducing the need for separate frontend tooling and JavaScript code.

## HTMX Example App:

```html
<h3> 
  Search Contacts 
  <span class="htmx-indicator"> 
    <img src="/img/bars.svg"/> Searching... 
   </span> 
</h3>
<input class="form-control" type="search" 
       name="search" placeholder="Begin Typing To Search Users..." 
       hx-post="/search" 
       hx-trigger="keyup changed delay:500ms, search" 
       hx-target="#search-results" 
       hx-indicator=".htmx-indicator">

<table class="table">
    <thead>
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Email</th>
    </tr>
    </thead>
    <tbody id="search-results">
    </tbody>
</table>
```

## Express.js app for HTMX frontend

```js
const express = require('express');
const app = express();

// POST /search route
app.post('/search', (req, res) => {
  // Simulating search logic
  const searchTerm = req.body.search;
  const searchResults = [
    { id: 1, firstName: 'John', lastName: 'Doe', email: 'john@example.com' },
    { id: 2, firstName: 'Jane', lastName: 'Doe', email: 'jane@example.com' },
  ];

  // Filter the search results based on the searchTerm
  const filteredResults = searchResults.filter((result) => {
    const firstNameMatch = result.firstName.toLowerCase().includes(searchTerm.toLowerCase());
    const lastNameMatch = result.lastName.toLowerCase().includes(searchTerm.toLowerCase());
    const emailMatch = result.email.toLowerCase().includes(searchTerm.toLowerCase());

    return firstNameMatch || lastNameMatch || emailMatch;
  });

  // Generate the HTML for search results
  const html = filteredResults
    .map((result) => `<tr><td>${result.firstName}</td><td>${result.lastName}</td><td>${result.email}</td></tr>`)
    .join('');

  // Simulating delay for illustration purposes
  setTimeout(() => {
    res.send(html);
  }, 1000); // Delayed response for 1 second
});

// Start the server
app.listen(3000, () => {
  console.log('Server started on port 3000');
});

```

## Choosing the Right Approach:

When deciding between React and HTMX, consider the following factors:

1. Project Complexity: If your application requires complex UI interactions, real-time updates, and a rich set of reusable components, React might be the better choice. React's component-based architecture and vast ecosystem provide the necessary tools to handle such scenarios.

2. Development Speed: HTMX can be an excellent choice for projects where simplicity and speed of development are paramount. With HTMX, you can add interactivity to your frontend directly, reducing the need for extensive JavaScript development and tooling setup.

3. Team Expertise: Consider the skills and expertise of your development team. If they are well-versed in React and comfortable with the React ecosystem, React may be the preferred option. On the other hand, if your team prefers a simpler frontend approach, HTMX could be a better fit.

## Conclusion:

Both React and HTMX offer powerful frontend solutions. React provides a comprehensive framework for building complex, interactive web applications, while HTMX simplifies interactivity by embedding declarative attributes directly in HTML markup. Choosing between the two depends on your project requirements, complexity, and the expertise of your development team. Evaluate the trade-offs, consider your specific needs, and select the approach that aligns best with your goals.