A quick tour of HTMX
Tags: webdev, htmx, javascript, fullstack
Published: 2024-02-27 14:11:56

In this blog post, I'll share my first impressions of HTMX, dissect what it is and its benefits, and provide examples to illustrate its power and potential. Let's dive into this intriguing technology that promises to bring back the simplicity and ethos of the original Web.

## What is HTMX?

*Here’s the pointy-haired professor definition:*

HTMX is an extension of HTML that gives you the ability to declaratively interact with server-side resources and generate dynamic client-side interactivity.

*Let’s break that down…*

### HTMX is a superset of HTML

HTMX introduces a set of custom attributes prefixed with **`hx-`**, such as **`hx-get`**, **`hx-post`**, **`hx-trigger`**, and **`hx-target`**. These attributes allow you to define the server interactions and client-side experience.

On top of that, another interesting aspect of HTMX is that you can use any element to trigger server calls, not just buttons or links:

```html
<div hx-get="/fetch-data" hx-trigger="click" hx-target="#data-container" hx-swap="innerHTML" style="cursor: pointer;">
    Click me to load data
</div>
```

### HTMX is declarative

HTMX adopts a declarative approach, allowing you to describe what you want to achieve directly in the HTML, rather than how to do it. This reduces boilerplate and makes your intentions clear by adding just a bit of markup.

For example, let’s say we want to load and display a set of user profiles from our backend server. Here is how you could accomplish this feature with React:

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

function UserProfiles() {
  // State to hold the fetched user profiles
  const [profiles, setProfiles] = useState([]);

  // Fetch user profiles on component mount
  useEffect(() => {
    fetch('/api/user-profiles')
      .then(response => response.json())
      .then(data => {
        setProfiles(data);
      })
      .catch(error => {
        console.error('Error fetching user profiles:', error);
      });
  }, []);

  return (
    <div id="profiles-container">
      {profiles.map(profile => (
        <div key={profile.id}>
          Name: {profile.name}, Age: {profile.age}
        </div>
      ))}
    </div>
  );
}

export default UserProfiles;
```

Now, here is the same functionality achieved with HTMX:

```html
<!-- Fetch and display user profiles -->
<button hx-get="/api/user-profiles" hx-trigger="click" hx-target="#profiles-container" hx-swap="innerHTML">
    Load User Profiles
</button>
<div id="profiles-container"></div>
```

### HTMX enables frontend interactivity

You can see how using the aforementioned attributes such as `hx-get` and `hx-post` and the user profiles fetch example above enable you to easily request and respond to server data. Here is another HTMX example, this time for a form submission:

```html
<form id="myForm" hx-post="/submit-form" hx-target="#responseMessage" hx-swap="outerHTML">
    <input type="text" name="username" required>
    <input type="email" name="email" required>
    <button type="submit">Submit</button>
</form>

<!-- This element will be replaced with the server's response -->
<div id="responseMessage"></div>
```

For basic apps, it’s easy to imagine not even needing a frontend framework like React!

## What are the benefits of HTMX?

### Simpler code

With HTMX, you can significantly reduce the amount of JavaScript required to make your web pages interactive. This not only makes your codebase cleaner but also more maintainable.

### Faster page loads

HTMX has the potential to drastically improve your page load times. It works directly with your existing HTML, meaning there's no need for the overhead of loading bulky JavaScript frameworks.

Second, HTMX natively supports the notion of interactivity “islands”, which are small chunks of the page that load independently as data arrives. You can design your site to load the essential content first, with more dynamic parts loading and becoming interactive as needed. This improves the perceived speed and responsiveness of your site.

Here is a simple example of the islands pattern. It’s trivial to use HTMX to load each section on its own.

```html
<h1>Welcome to HTMX News</h1>

<!-- Main Article Island -->
<div id="main-article" hx-get="/main-article" hx-trigger="load" hx-swap="innerHTML">
    Loading main article...
</div>

<!-- Related Articles Island -->
<div id="related-articles" hx-get="/related-articles" hx-trigger="load" hx-swap="innerHTML">
    Loading related articles...
</div>

<!-- Comments Island -->
<div id="comments-section" hx-get="/comments" hx-trigger="load" hx-swap="innerHTML">
    Loading comments...
</div>
```

### Backend devs can be full stack

Since HTMX moves much of the client-side rendering back into the server, backend developers can more readily use the tools and patterns familiar to them to contribute to the frontend. This paradigm is closer to the original days of full-stack development, before the advent of single-page application frameworks.

### True (web) client agnosticism

Since HTMX leverages standard HTML, it works across all modern browsers without requiring special adaptations or polyfills. This ensures your applications are accessible to a wide audience without extra work.

However, to support other types of clients, such as native mobile apps, you will probably still need a pure data API (e.g. JSON API).

### Progressive enhancement

HTMX fits perfectly with the philosophy of progressive enhancement. You can start with a fully functional HTML page, and enhance or degrade the experience depending on the capabilities of your client. This ensures that your site remains usable even if JavaScript fails or is disabled.

## Is HTMX the future?

Depends on who you ask! Single-page frameworks like React are powerful, but there is a growing sentiment that the design patterns have become too complicated and apps too bloated.  Browser capabilities have grown tremendously since the original days of AJAX and jQuery, and we can rely on them more without the use of third-party JS libraries.

HTMX addresses a real need for simplicity and efficiency in web development, challenging the prevailing complexity of SPA frameworks. It's a powerful library for developers looking for a more straightforward, maintainable approach to building interactive web applications. 

In conclusion, my first impressions of HTMX are overwhelmingly positive. It feels like a return to the basics of the web, enhanced with modern capabilities. For those of us yearning for simpler times without sacrificing the interactivity and dynamism users expect, HTMX offers a compelling solution.