DEV Community

Cover image for A quick tour of HTMX
Jaydev Mahadevan
Jaydev Mahadevan

Posted on

A quick tour of HTMX

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:

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

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:

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;
Enter fullscreen mode Exit fullscreen mode

Now, here is the same functionality achieved with HTMX:

<!-- 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>
Enter fullscreen mode Exit fullscreen mode

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:

<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>
Enter fullscreen mode Exit fullscreen mode

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.

<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>
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (1)

Collapse
 
kortizti12 profile image
Kevin

In my opinion, HTMX isn’t a replacement for well-known frameworks. Rather, it’s a solution for back-end focused full-stack developers. While HTMX is indeed powered by JavaScript, it’s more useful to think of it as an updated version of HTML to address today’s needs. HTMX is nowhere near as popular as industry-standard frameworks like React.

It’s worth mentioning that HTMX can be easily integrated to existing projects without a complete overhaul. One of the most significant advantages of using HTMX is its ability to produce smaller codebases. Since HTMX relies on adding attributes directly to HTML elements to define behavior, there’s no need for verbose JavaScript code to manipulate the DOM or handle events. This reduces development time and results in a more readable and maintainable codebase. In some cases, switching from React to HTMX has resulted in a codebase that’s a third of the size!

HTMX’s simplicity, performance, and ease of use make it a great choice for projects where quick deployment of lightweight scripts and page-load performance are prioritized. However, it may not be the correct choice for applications that require extensive client-side logic and state management, where traditional JavaScript frameworks might still hold the edge.

As with any choice between frameworks, there are always trade-offs to consider, and HTMX is no exception. Your decision to switch to HTMX or use it in a new project should be based on your unique project requirements, team expertise, and the desired balance between ease of development and the depth of interactive features.

I recommend reading this article from Facundo Corradini that describes more about HTMX perks and limitations: scalablepath.com/front-end/htmx