Taking a Closer Look at Phoenix LiveView

2 minPhoenix

Phoenix LiveView is a library that allows you to build web applications that offer rich, real-time user experiences while avoiding the massive complexity associated with writing and maintaining single page applications (SPA).

What is a single page application (SPA)?

A single-page application (SPA) is a web application or website that operates within a single HTML page. Unlike traditional multi-page applications, SPAs dynamically update the content on the page without requiring a full page reload. They provide a more seamless and interactive user experience by using JavaScript frameworks like Angular, React, or Vue.js to handle client-side rendering and routing.

The user experience can be much better (if done right) but the complexity may also increase as we need to add multiple frontend related technologies as frameworks, libraries, state management, testing and other dependencies.

Phoenix LiveView aims to keep the user experience but minimising the complexity.

SPA Simple Mental Model

Firstly, single-page applications (SPAs) request HTML, JavaScript, and CSS from the server and may fetch additional data for rendering. A typical SPA includes a data model, client logic, and view-related functions, communicating with the server over HTTP and possibly WebSockets for real-time features.

Phoenix LiveView, however, operates differently. When an HTTP request is made, the server responds with fully rendered HTML, which is beneficial for SEO and faster page loads. Immediately after loading, a WebSocket connection is established. Unlike SPAs, the model, logic, and view components reside in a client-specific process on the server, not the browser.

Phoenix LiveView Diagram

As an example, consider a simple counter app. The counter value, or state, lives on the server. Functions handle increment and decrement events, passed from the browser to the server via WebSocket. Changes in state cause the server to automatically render and send the changes in the view to the browser.

While you might worry about scalability, Elixir processes, such as the LiveView process, are extremely lightweight. They can handle large numbers, with tests successfully demonstrating two million concurrent WebSocket connections on a single Phoenix server. Despite sending browser events to the server for rendering and updating the view, efficiency is maintained through state tracking and diffing algorithms on both server and client sides.