DEV Community

Cover image for Why you should choose HTMX for your next project

Why you should choose HTMX for your next project

Turcu Laurentiu on October 19, 2023

In this article, we will aim to understand why you should consider HTMX as a replacement for React next time you choose a tech stack for a web app....
Collapse
 
artydev profile image
artydev • Edited

Once upon a time there was : mavo.io from Lea Verou.
Nothing really new in this world

Juste for smiling...

Collapse
 
turculaurentiu91 profile image
Turcu Laurentiu

Nice, never heard about that!

Collapse
 
artydev profile image
artydev

E un piacere :-)

Collapse
 
nicolasdanelon profile image
Nicolás Danelón

So now my API will return this mixture of HTML, cool. what if I need to use the same API for a backend website, a mobile application and some third party companies use that API too?
This HTMX trend is one more thing that contribute to the JavaScript fatigue. more of the same.

Collapse
 
turculaurentiu91 profile image
Turcu Laurentiu

You ain't goona need it

In short, imlementing features because you might need them in the future is bad, but if you need them right now, then go ahead and use API JSON. I am just presenting an alternative!

Collapse
 
virtualmachine profile image
ByteCodeProcessor

YAGNI feels at odd with "Design with change in mind".

Collapse
 
developerkwame profile image
Oteng Kwame

You can keep the api still running and pass the results to the HTML that will be returned to the server. I guess you get what I'm saying here.

Collapse
 
dansasser profile image
dansasser

I absolutely love HTMX! I am currently using it with Astro 3.0 and some hyperscript as well. With Astro I can use a mix of HTMX, React, Vue and a few other frameworks since it uses Vite for the build. With the OBB-SWAP I am able to update multiple DOM and make my components as interactive as needed with ease.

Collapse
 
jankapunkt profile image
Jan Küster

The question is how well it Integrates with existing frontend engines. The strict limits between a static page and an spa disappear more and more. Sometimes a great portion of a webapp is static while a certain area or page is very complex, state-driven and highly interactive.

This creates the situation that most of the time react is way too much for the static stuff but necessary for the complex stuff.

In such a scenario I would definitely try a hybrid setup with ssr+htmx for the static stuff but stateful react for the complex ones.

How well would that perform?

Collapse
 
turculaurentiu91 profile image
Turcu Laurentiu

You are not limited in any way by HTMX, you can have react parts in your website, or web components or whatever. The only issue you can get is when a part of the DOM of a react component is updated by HTMX and the component is re-rendered, react will override those changes.

But you can easely overcome by not doing that and communicate between the two worlds using browser custom events.

You can definetly submit a react form using HTMX, it will work. You can have, for example, a form dialog modal rendered and managed by react, but when you submit it, have it submitted using HTMX!

But I might suggest that you give a look at alternatives like Alpine.js or Lit web components or Solid.js for a more lightweight approach for reactive scripting.

Collapse
 
jankapunkt profile image
Jan Küster

Thanks for the detailed and thorough response 👍

Collapse
 
dsaga profile image
Dusan Petkovic

The shift from client side rendering back to mostly server side rendering is apparent of lately, but it is justified as from what I've experienced front-end frameworks like React were used way too much without a real need.

You're spot on on the complexity of front-end stacks increasing, its now even more complicated with SSR.

One thing I would add, for some of the problems you mentioned between front-end and backend teams, I wouldn't say its related to react or any other front-end framework, as the efficiency between the teams depends on the setup, usually its not a problem, as API contracts are defined beforehand, and the front-end team has Open API docs to generate all interfaces from.

Great read anyways!

Collapse
 
pvivo profile image
Peter Vivo

HTMX convert many interaction form JS tohx- tag system. The casual webpage this system will pass work to server, which is really fine, but give extra works to server side programming or other words front end developer need to work much closer to backend developer collogues, what do you think?

Of course I saw the potential in HTMX, but I think my React thinking is much closer to qwik solution, which is also give a good answer to minimalize the client size JS code size.

Collapse
 
turculaurentiu91 profile image
Turcu Laurentiu

Yes, I agree that HTMX tightens the link between back-end and front-end, what I would argue is that it's a desired outcome IMHO, as it will reduce the need of interface agreements and documentation. You can acutally spend those resources on implementing stuff that brings value to your users!

And for the server workload, it might be true, but when is the last time when you fetched only the data you needed from your API?
Most of the time you overfetch, you don't only fetch the user name and email to show it in the picklist, you fetch their profile, their employee profile, their employer data, their department, their department budget and maybe what they eat for luch yesterday 😄

Collapse
 
ohidere profile image
ohidere

As a frontend developer, this HTMX does not attract me even a little bit. It seems annoying to work with and I'm passing.

Collapse
 
kortizti12 profile image
Kevin

I really liked this post! I’ve been exploring more and more about JavaScript libraries that simplify front-end interactions and make web apps more maintainable and performant. HTMX has many benefits, to be sure. But, as with any tool you choose, there are some tradeoffs.

Here are a few:

  • Harder to find skilled developers: Finding developers skilled in HTMX can be challenging since it is less popular than frameworks like React. However, its foundation on core web technologies makes it easy for experienced developers to learn quickly.
  • Compatibility with mobile apps: HTMX's approach of sending HTML over-the-wire can complicate compatibility with mobile apps and other platforms, requiring workarounds that may add complexity.
  • No type safety: HTMX lacks type safety, unlike TypeScript, but this is mitigated as most logic is handled on the back-end.

As always, it will vary based on the needs of your project, your team’s expertise, and the particular features you’re looking to build. Here are three instances where HTMX might be preferred:

  1. When SEO is critical
  2. When maintaining JS-rich client-side frameworks is complex or resource-intensive
  3. When you want to handle the business logic mostly on the server side

I recommend reading this article from Facundo Corradini that expands on the benefits and limitations of HTMX: scalablepath.com/front-end/htmx

It is really exciting that libraries such as HTMX are becoming more popular and people are starting to share this knowledge widely.

Collapse
 
meatboy profile image
Meat Boy

With HTMX we are evolving. Just backwards. I hope the next boom will be for the plain HTML or some good old template engine

Collapse
 
turculaurentiu91 profile image
Turcu Laurentiu • Edited

The problem is that the HTML and the browser API didn't evolved enough to allow native SPA like websites, but that started to chage with the new transition API developer.chrome.com/docs/web-plat...

Collapse
 
melphindev profile image
MelphinDev

I had never heard of HTMX before. I'm going to try it.
Thank you for a very detailed article, by the way.

Collapse
 
efpage profile image
Eckehard

HTMX provides a fine grained update of page elements. In theory, this reduces the ammount of data to be served and should make your applications fast.

But what about latency on the web? Each request takes some time to be answered. What happens, if your connection is slow or not stable? We often see that fetch-requests may delay your page update. In HTMX, fetching little parts of your page is the backbone. Does this harm the user experience?

Collapse
 
nimmneun profile image
Stefan

If you're app has to be usable offline and you have to keep track of state changes, it's outside of the scope HTMX (alone) solves.

Collapse
 
efpage profile image
Eckehard

Good point! One argument for HTMX are short response times, and I´m really curious whether this is actually achieved in everyday life. I would not like to wait for every second click because my line is busy...

Thread Thread
 
nimmneun profile image
Stefan

I actually haven't seen much of a difference in response times, but I'm still in an early exploration phase with HTMX and only using it for private stuff.

Personally I feel it's a bit more geared towards projects that don't use JS/TS in the backend and just need some "ajaxy" reactivity. E.g. I can just render all my templates and HTML partials/fractals/components in the backend where I fetch/generate the data (using the template engine of my backend), return it as a response and be done with it. So as a mainly Go/PHP dev it's quite nice and easy to test/validate expectedHTML vs renderedHTML via string comparison xD.

Thread Thread
 
efpage profile image
Eckehard

It seems, HTMX is very open to hybrid approaches. Maybe we should use different technologies together to build UI´s:

  • Some elements of the page can be rendered on the server, so you can deliver a more or less static page
  • Some dynamic elements can be easily handeled with HTMX
  • There are still some interactions that are better handeled on the client using Javascript. Anything you do not want any delay caused by a slow web.

I´m still not clear if there is any easy way to manage those pages.

Thread Thread
 
turculaurentiu91 profile image
Turcu Laurentiu

Yes, there is no getting around scripting, but you can take a look at alternatives as Alpine.js, hyperscript or even Lit before you decide to render everything in a vDOM and introduce all the react stuff to your project.

Thread Thread
 
nimmneun profile image
Stefan • Edited

I'm playing with the websockets extension right now on a project where my go client has a few 100 open connections to exchanges, aggregates the data into a Redis cache and serves the price aggregates back into a frontend in 10ms intervals. I'm still fiddling with some stuff, but so far its looking quite promising ... I basically have almost no JS remaining and everything is done via the hx attributes.

I also like this part (c&p from docs):

After an unexpected connection loss due to Abnormal Closure, Service Restart or Try Again Later, reconnecting is tried until successful. The default reconnection interval is implemented with the full-jitter exponential-backoff algorithm. Own implementations can be provided by setting htmx.config.wsReconnectDelay to a function with retryCount as its only parameter.

Collapse
 
brense profile image
Rense Bakker

No offense, but the reason react exists is because we found out through frameworks like angular that extending the html syntax compared to just using JavaScript syntax is a bad idea... Not only does it force developers to learn yet another syntax, it also means that you have to reinvent the wheel on every problem that was already previously resolved by JavaScript view libraries...

Collapse
 
zsomborjoel profile image
Zsombor Joel Gyurkovics • Edited

No offense, I had to.

But this is actually about using JS and overly complex FE frameworks all the time. Not everyone loves JS. Some of us would like to create a decent web app in his loved programming language.

Image description

Collapse
 
brense profile image
Rense Bakker

Html is not a programming language though... I'm aware that there are many groups who are religiously against react or even JavaScript frameworks in general. Personally I don't really believe in forcing my religion on anyone. All I can say is, there's a reason why JavaScript frameworks were created and why they became popular. If you disagree with the reasons those frameworks exist, by all means, just use HTML. Why even invent HTMX? It is really just another JavaScript framework that uses a (not)HTML syntax, like angular JS.

Thread Thread
 
zsomborjoel profile image
Zsombor Joel Gyurkovics • Edited

Most of the Backend dev community not using JS often (me either). But they want to develop web UI-s efficiently (possibly in their programming language of choice). This is the best tool for that with a templating engine. Minimal simple abstraction and great performance due to hx-target and hx-swap.

As FE engineers wants to replace part of BE with Next.js for example.

BE engineers would love to replace some of the FE needs with HTMX. (+ hyperscript or AlpineJs)

More details here in this great interview with the creator of HTMX: Behind HTMX : Carson Gross

Thread Thread
 
brense profile image
Rense Bakker

Aha, so that's what it is about. BE engineers feel threatened by NextJS and JS framework encroaching on "their" territory? My stance remains the same. Instead of being scared of change, why not research what makes these JavaScript frameworks so popular? There's a whole history and actually really valid reasons behind it :)

Collapse
 
booooooooooo profile image
BOOOOOOOOOOO

Nah, Javascript makes it just over-complicated now. We don't need to stick to javascript because there are a bunch of good programming languages. Javascript is just like a hammber of a metaphor "hammer and nails".

Collapse
 
brense profile image
Rense Bakker

There are not that many languages in the browser.

Collapse
 
adaptive-shield-matrix profile image
Adaptive Shield Matrix

What about DX?

  • Biggest/Best feature of React is HMR (Hot-Module-Reload) - reloading components without the loss of state.
  • Developing for/with Next.js / Server components -> completely sucks, because even if it supports HMR it takes something like 5-10 seconds (on a not Macbook M1/M2) for the components to reload and me as the developer to see the changes
  • Developing with Vite (in comparison) - is pure joy and bliss.

React-Server-Components

  • do not really help to simplify you app, because you can't use them for interactivity -> you still need to add client components for that
  • it forces you to balance client vs server components, their boundaries and data passing -> complex mental gymnastics for your as the dev

HTMX + golang templates - seems like the best choice to skip React (for backend engineers)

How does HTMX allow to test components in isolation (storybook in React ecosystem)?

  • Its completely fine not testing components in isolation for small hobby projects, but what will you do if you have 50-100k lines of code?
Collapse
 
turculaurentiu91 profile image
Turcu Laurentiu • Edited

As a first argument, HTMX will help you reduce the amount of code from houndreds of thousends to only tens of thousends.
linkedin.com/feed/update/urn:li:ac...

And if you want to test, you can test it the same way you test JSON API, you call the endpoints and insepct the resulted HTML.

And about HMR, you don't have any build step. You can just refresh the page or have your backend technology of choice refresh it for you and you have your changes presented in the browser.

Collapse
 
adaptive-shield-matrix profile image
Adaptive Shield Matrix • Edited

Still no HMR?

So you are okay to ignore improvements to developer experience (biggest advantage of react) ?
You are okay going back 20 years in time to how software was developed earlier?

I can remember 10-15 years ago how I used Java -> GWT (Ui lib + js) compiler to develop GUIs and I can tell you now that it sucks for business logic heavy, highly interactive web apps.
You want to see how a different color/font/padding looks like? You have to wait for full page reload and THEN still have to click through 3-5 elements to get to the same ui state to see how it looks. Repeat min 100x per day. It SUCKS

Thread Thread
 
zsomborjoel profile image
Zsombor Joel Gyurkovics

If you are a Java dev then Spring Boot has live reload with dev tools, which would mimic HMR of React.

Thread Thread
 
adaptive-shield-matrix profile image
Adaptive Shield Matrix

Live Reload will never mimic HMR because you lose the local state in your Browser.
This is not important for low interactive (nearly static or single SSR rendered) sites but this is highly important for high interactive web apps.

Example: You open a dialog, type something into a form input to see if an error message shows up -> HMR reloads changes without your losing state (dialog keeps open, input retains value) while live reload throws everything away. With live reload you have to open the dialog again and type something in to the input again, repeat that 100x a day and you will start the value in HMR.

I mean, I was were, 15 years ago with SSR rendered/generated/transpired websites with Java -> GWT, I am not going back.

Collapse
 
sm0ke profile image
Sm0ke

great content. ty

Collapse
 
andberry profile image
Andrea Berardi

Great post, thank you so much!

Collapse
 
tommiller profile image
Tom Miller

A most informative article. I am currently exploring the possibilities of htmx with Go server-side rendering. Just referenced this article on the Learning Go for Data Science site.

Collapse
 
turculaurentiu91 profile image
Turcu Laurentiu

Thank you! I heard that go has great templating capabilities, I have to give it a try someday!

Collapse
 
petezahad profile image
Mathias Stocker

Thanks for mentioning Turbo!
Great Tool together with Stimulus

Collapse
 
karlkras profile image
Karl Krasnowsky

And many other solutions that I forgot about or never heard about!

Yeah, ejs is an example.

Collapse
 
karlkras profile image
Karl Krasnowsky

Nice article. Good work!

Collapse
 
karlkras profile image
Karl Krasnowsky

The numbers are made up, I don't have any research to back this up

Sounds like a politician, but you're admitting it 😄

Collapse
 
yellowcmd profile image
Yellow

Amazing article, really loved reading through it, congrats!

Collapse
 
zsomborjoel profile image
Zsombor Joel Gyurkovics

FYI - If anyone has more question, then you should visit htmx discord channel as well. Community quite welcoming and active there.

Collapse
 
tsolan profile image
Eugene • Edited

If you talk about frontend, why do you add up backend tasks to the list of problems/complexities of frontend?
I didn’t get the point. HTMX is an abstraction layer built in js and so, comes at a price. The question: if react is overengineering for a simple web app, why shouldn’t I use vanilla js, but bother myself with another library and its specific syntax?

Collapse
 
zsomborjoel profile image
Zsombor Joel Gyurkovics

Because HTMX is simple. You just write hx-get + hx-target and the swapping is done. In vanilla js it would take more lines for sure.

Collapse
 
rtacconi profile image
Riccardo Tacconi • Edited

The issue is that React can be use (with React Native) to create mobile and desktop applications and HTMX does not