SINGLE PAGE APPLICATIONS: HTMX AND REACT; WHERE SERVER SIDE MEETS FRONT-END

uba joseph ugochukwu
8 min readFeb 3, 2023

--

Abstract

Discover the benefits of Single Page Applications in this comprehensive article. Learn about the latest SPA architecture and compare React and HTMX, two popular SPA frameworks. Enjoy faster user interactivity, seamless navigation, and efficient development. Gain insight into the client-side and server-side components, the DOM and JSON data format, and the advantages and disadvantages of React and HTMX. Whether you’re a seasoned developer or just starting, this article provides all the information you need to choose the right SPA framework for your project. Get started now!

want learn HTMX and Django? something big is coming your way soon at https:codebrilliantacademy.com/

Introduction

The evolution of the Web in the early 2000s has led to the increasing complexity of website logic and information platforms. As a result, traditional static websites and dynamic solutions based on content management systems have been replaced by full-featured web applications. These applications are based on a client-server architecture, where the business logic is executed on the server (back-end) and the client interacts through the user interface in their browser (front-end). This approach minimizes page reloads and allows real-time HTML content generation.

One of the key techniques of Web 2.0 is Single-Page Applications (SPAs), which use AJAX, React, and HTMX to asynchronously fetch and update data without refreshing the page.

Why This Article?

This article aims to provide insight into the Single Page Application (SPA) architecture and its use in developing native-like applications for browsers. The article also explores the need for alternatives to Hypermedia, such as HTMX, to make SPAs less reliant on Javascript frameworks such as React.

The objective of writing this article is to provide a comparison of the pros and cons of using REACT and HTMX in single page applications. This comparison is intended to help developers choose the appropriate SPA framework in different scenarios, taking into account factors such as code simplicity, resource consumption, and ease of use for end users.

Additionally, the article aims to provide a comprehensive overview of the benefits of using Single Page Applications in web development, including improved user interactivity, reduced lag time, and streamlined development processes. By exploring the use of React and HTMX in SPAs, this article aims to provide a deeper understanding of how these technologies can be leveraged to create fast and efficient web applications that meet the needs of both developers and end-users.

Single Page Application: Overview and Architecture.

A Single Page Application (SPA) is a type of web application that is designed to run within a single HTML web page. Unlike traditional web applications, which rely on server-side interactions to reload new HTML pages for each change of context, SPAs execute most of the application’s logic on the front-end, using HTML, CSS, and Javascript. This reduces the number of page reloads and provides a more responsive and smooth user experience.

In a traditional web application, the client-side consists of HTML, CSS, and Javascript, while the server-side consists of API logic and a database. When an HTTP request is made, a new web page is loaded in the browser, and all resources, including CSS, Javascript, and images, are fetched from the server. This leads to slow performance and poor user interaction due to the repeated loading of resources.

Traditional web application

In contrast, an SPA relies on local storage in the browser and only makes asynchronous, limited server-side interactions for resource retrieval from an API endpoint. This eliminates the need for repeated loading of resources and provides a more seamless and responsive experience for the user.

The Document Object Model (DOM)

is a programming interface for HTML and XML documents that represents the document structure in a parent-child relationship and allows for access and manipulation through Javascript. JSON (JavaScript Object Notation) is a language-independent data format used to transfer data between the server and client.

Architecture Of An“SPA”

An SPA architecture is distinct from traditional web apps, where the browser acts as a client. After loading the shell of the app, including the HTML page and relevant Javascript/CSS files, the app framework fetches the business logic, initializes the controllers and retrieves the HTML partial views and data model. Two-way binding between the view and model allows updates to the model to be reflected in the view and vice versa. The model resides in the browser’s local storage and is synchronized with the server-side via API requests. The server’s role is to serve multiple clients and provide resources based on API endpoints. The SPA also handles DOM events and allows navigation through routing, which is driven by the model and configured in a configuration file. Modularization of the application through dynamically generated routes benefits the development process and facilitates unit and end-to-end testing.

Architecture of an SPA

React.js As an SPA Library

React.js is a JavaScript library used to create user interfaces in a predictable and efficient manner using declarative code. It is commonly used to build single-page applications and mobile apps, or as a component of complex applications when combined with other libraries. The main challenge that React addresses is the creation of massive applications with changing data. In this context, it may be viewed as the “View” component in the Model-View-Controller (MVC) pattern.

In React, everything is represented as an “element” or “component”. Components are built using JSX, which is a way of declaring HTML content as variables, functions, etc. Each component has a lifecycle divided into three phases: Mounting, Updating, and Unmounting. Mounting refers to inserting components into the Document Object Model (DOM), while updating refers to changing the state or properties of a component.

HTMX As an SPA LIbrary

Htmx is a Hypermedia library that allows developers to access AJAX, CSS Transitions, WebSockets, and Server-Sent Events directly in HTML using attributes. It operates according to the Hypermedia Driven Application (HDA) architecture, which combines the simplicity and flexibility of Multi-Page Applications (MPAs) with the better user experience of Single-Page Applications (SPAs). The HDA architecture uses a declarative HTML syntax to achieve better front-end interactivity and interacts with the server using hypermedia (HTML) rather than non-hypermedia formats (JSON).

How HTMX Works

“HTMX is a modern, client-side library that allows for dynamic updates to web pages without the need for full page reloads. In traditional web applications, user interactions with the page such as clicking a link or submitting a form trigger either a GET or POST request to the server, with the server responding by sending back a new HTML template.

With HTMX, these interactions can trigger specific updates to specific pieces of the DOM, rather than a full page reload. This provides a more seamless user experience, with real-time updates and validations happening before the user submits their information. HTMX also offers a wider range of triggers for server requests, such as mouse movement or typing in an input field.

The library utilizes hypermedia, providing direct access to modern browser features via HTML, rather than using JavaScript. On the server side, HTMX leverages the original web programming model by responding with HTML, rather than JSON.

In summary, HTMX enables dynamic, real-time updates to web pages while staying within the traditional web programming model, providing a more efficient and seamless user experience.”

Drawbacks of React in Single-Page Applications (SPAs)

1. Scalability Challenges: In traditional web apps, functionality is spread across multiple pages, allowing for easy updates to individual pages. However, in SPAs, components are tightly integrated, making changes to a widely used component a challenging task that can impact the entire application. Therefore, SPAs must be designed with future changes in mind, requiring developers to consider scalability at the design stage.

2. Architectural Constraints: Switching to a new framework in traditional multi-page applications (MPAs) is easily done by updating one page at a time. However, SPAs do not offer such incremental changes and require a full port of the entire application to a new framework. This requires careful planning and execution to ensure a seamless transition.

3. Search Engine Optimization Issues: SPAs present a challenge for web crawlers as they only index the main page and ignore additional pages, leading to poor search engine optimization (SEO). Google is continuously updating its algorithms to address this issue, and SEO agencies have some workarounds, but SPAs are still not always indexed correctly.

4. JavaScript Dependency: Since SPAs rely heavily on JavaScript frameworks, they may not load in browsers where JavaScript is disabled, which is a concern for some users who disable it to improve loading speed.

5. Routing for Navigation: The routing logic in SPAs handles in-app navigation, making it crucial to consider any scenarios where components may not be loaded on time. Routing can be enabled through the use of a hash in the URL or HTML 5 pushState, with popular SPA development frameworks offering their own routing solutions.

6. Memory Leaks: SPAs are prone to memory leaks, especially when poorly coded, as the page persist for a prolonged period without being fully reloaded, potentially slowing down even high-performance machines.

7. Security Risks: With SPAs, clients download the entire application, providing more opportunities for reverse engineering and potential vulnerabilities. It’s essential to implement secure client-side logic (such as input validation and authentication) and to verify it on the server, allowing access based on user roles.

Hyper Media Approach (HTMX) vs React Approach

JavaScript frameworks such as React and Vue.js create SPAs by making requests to a server and receiving data in JSON (JavaScript Object Notation) format. However, this approach comes with its own set of drawbacks:

1. Large Initial Download: The initial request for an SPA sends a significant amount of JavaScript code, leading to a heavier download compared to traditional web applications where only the required HTML travels between the server and user.

2. Blank Initial Page: SPAs start as a blank page, filled in by JavaScript, which is not ideal for SEO as search engine crawlers only see the initial blank page.

3. Complicated Data Requests: Simple tasks like logging in a user require significant overhead to ensure that passwords are not exposed in requests.

HTMX extends and generalizes the core concept of HTML as hypertext, unlocking a broader range of possibilities within the language: 4. Any element can issue HTTP requests, not just anchors and forms.

1. Any event can trigger requests, not just clicks and form submissions.

2. Any HTTP verb can be used, not just GET and POST.

3. Any element can be updated by the request, not just the entire window.

Conclusion:

Single-page applications have become a popular choice for web development projects. They offer fast loading speeds, a seamless user experience, and quicker time to market. However, it is crucial that SPAs are planned and developed carefully by experienced teams.

In terms of architecture, HTMX offers numerous advantages over React when it comes to building SPAs. HTMX extends the fundamental concept of HTML as hypertext, resulting in a more versatile and flexible solution. With HTMX, any element can issue an HTTP request, trigger a request through any event, and use any HTTP verb. Additionally, any element, not just the entire window, can be targeted for updates.

Furthermore, HTMX’s approach to data requests is much simpler, as it avoids the complexities that arise in React, especially in cases such as logging in a user, where additional measures need to be taken to ensure the security of sensitive information.

Overall, HTMX presents a modern and innovative approach to building SPAs that should be considered by developers seeking to take their web projects to the next level.

--

--