Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 48 ยท Real-World Elixir

Phoenix LiveView

Learn how Phoenix LiveView builds interactive pages with server state over a websocket: mount, assigns, events, forms, PubSub updates and testing.

Most interactive web pages are built from two programs: a JavaScript front end that holds the UI state, and a server API that holds the truth. Phoenix LiveView removes the split. Each open page is backed by a lightweight Elixir process on the server that keeps the state, receives events from the browser and sends back only the parts of the HTML that changed.

You already know the building blocks from Phoenix: Web Applications and from processes. A LiveView is simply a process whose state is a map of assigns and whose output is HTML. Real Phoenix cannot run on this site, so the Elixir blocks below are read-only, and the editors use a JavaScript model of the idea. I will say clearly which parts are real and which are a stand-in.

One page, one process

First request A normal HTTP request returns full HTML.
Websocket The page connects back to the server.
State A process keeps the assigns.

The browser stays thin. The server owns the state.

1 / 2

A first LiveView

A LiveView is a module with mount/3, render/1 and event handlers. This counter is the classic first example:

ELIXIR
defmodule MyAppWeb.CounterLive do
  use MyAppWeb, :live_view

  def mount(_params, _session, socket) do
    {:ok, assign(socket, count: 0)}
  end

  def handle_event("increment", _params, socket) do
    {:noreply, update(socket, :count, &(&1 + 1))}
  end

  def handle_event("decrement", _params, socket) do
    {:noreply, update(socket, :count, &(&1 - 1))}
  end

  def render(assigns) do
    ~H"""
    <h1>Count: {@count}</h1>
    <button phx-click="decrement">-</button>
    <button phx-click="increment">+</button>
    """
  end
end

You wire it up in the router with a single line, live "/counter", CounterLive, inside a scope that uses the browser pipeline. Let us read the parts.

  • mount/3 runs when the page starts. It receives URL params, the session and a socket, and returns {:ok, socket} with the initial assigns.
  • assign/2 puts values into socket.assigns. In the template you read them as @count. update/3 changes one assign with a function.
  • phx-click="increment" tells the client: when this button is clicked, send an event named "increment" to the server.
  • handle_event/3 receives the event name, a map of parameters and the socket, and returns {:noreply, socket} with the new assigns.
  • render/1 is a function of assigns. The ~H sigil is HEEx, the same template language you met with Phoenix; it checks your HTML at compile time.

The socket is just a struct that carries the assigns. You never mutate it: every helper returns a new socket, in line with immutable data.

The lifecycle: two mounts

When someone visits /counter, the first request is an ordinary HTTP request. Phoenix calls mount/3, then render/1, and sends complete HTML. That is good for search engines and for speed, because the user sees content before any JavaScript runs.

Then the small LiveView JavaScript client opens a websocket and the server starts a new process that calls mount/3 again, this time connected. From then on, events and updates flow over the socket.

sequenceDiagram
    participant B as Browser
    participant S as LiveView process
    B->>S: HTTP GET /counter
    S-->>B: full HTML (static render)
    B->>S: websocket connect
    S-->>B: connected, same page
    B->>S: event "increment"
    S-->>B: diff: only the number changed

The page is rendered twice: once as plain HTML, then again when the websocket connects.

Because mount/3 runs twice, avoid expensive or side-effecting work in it without checking connected?(socket). Subscribing to a PubSub topic is the usual example: you only want to subscribe in the connected mount.

Why diffs are small

On every render, LiveView separates the template into static parts (the HTML around your expressions) and dynamic parts (the values of @count and friends). The static parts are sent once. After that, only the dynamic values that changed travel over the wire. Clicking the plus button sends a tiny event and receives something like a single changed string. On the page, the client patches the DOM in place.

This is also why you should keep assigns small and avoid recomputing big structures: LiveView tracks which assigns a template part reads, and only re-evaluates the parts whose assigns changed.

Try it: the update loop in JavaScript

The editor below is a model, not LiveView. It keeps the assigns in a plain object, applies event handlers that return new assigns, and prints a "diff" by comparing the rendered dynamic values. Real LiveView sends a compact structure and patches the DOM; the mental model is the same.

JS A counter LiveView, modelled in JavaScript

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that set_step only changes the step part, and the counter title is absent from that diff. That is the same idea as LiveView's change tracking. Note also that the handler never edits the old assigns, it returns a new map.

Forms, validation and navigation

Forms work with phx-change and phx-submit. In current Phoenix, you turn a changeset into a form with to_form/1, and the <.form> and <.input> function components render it:

ELIXIR
def handle_event("validate", %{"user" => params}, socket) do
  changeset = Accounts.change_user(%User{}, params)
  {:noreply, assign(socket, form: to_form(changeset, action: :validate))}
end

def handle_event("save", %{"user" => params}, socket) do
  case Accounts.create_user(params) do
    {:ok, user} ->
      {:noreply, push_navigate(socket, to: ~p"/users/#{user}")}

    {:error, changeset} ->
      {:noreply, assign(socket, form: to_form(changeset))}
  end
end

Each keystroke can send a validate event, so errors from your Ecto changeset appear live, with the same validation rules the server enforces on save. push_navigate/2 moves to another LiveView over the same socket, and push_patch/2 changes the URL of the current one; in that case handle_params/3 runs so you can react to the new query string, for example a sort order or a page number.

For long lists, streams (stream/3) let the server send only new rows without holding the whole list in memory, which matters for feeds and logs.

Real-time updates with PubSub

Because each page is a process, it can receive messages. Phoenix ships with Phoenix.PubSub, a publish and subscribe system. A LiveView subscribes to a topic in mount, and any process, such as a controller, a background job or another LiveView, can broadcast to it:

ELIXIR
def mount(_params, _session, socket) do
  if connected?(socket) do
    Phoenix.PubSub.subscribe(MyApp.PubSub, "scores")
  end

  {:ok, assign(socket, scores: Scores.list())}
end

def handle_info({:score_updated, score}, socket) do
  {:noreply, update(socket, :scores, &[score | &1])}
end

# Somewhere else, after a score is saved:
Phoenix.PubSub.broadcast(MyApp.PubSub, "scores", {:score_updated, score})

handle_info/2 is the same callback you know from GenServer. Every open browser tab on that topic updates at once, with no polling. The next editor models this with plain functions.

JS PubSub between three open pages (JavaScript stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

When a real LiveView process ends, because the tab closed or the socket dropped, the PubSub subscription disappears with it automatically. The model needs the explicit close function for that.

What to watch out for

  • State lives on the server. Each connected user costs some memory. Keep assigns lean, use streams for big collections, and do not store large structs you can fetch on demand.
  • Reconnects restart the process. If the websocket drops, the client reconnects and mount/3 runs again. Anything that matters must be reproducible from the URL, the session or the database.
  • Latency is real. Every event is a round trip. Use phx-debounce on text inputs, and client-side commands (Phoenix.LiveView.JS) for pure UI effects such as toggling a menu.
  • Never trust event params. They come from the browser and can be forged. Authorize in the handler, just like in a controller.
  • Do slow work elsewhere. A LiveView that blocks in a handler freezes that user's page. Use start_async/3 or send the work to a Task and handle the result in a callback.

Testing

Phoenix.LiveViewTest lets you drive a LiveView without a browser. live(conn, "/counter") returns the view, render_click/2 fires an event and returns the new HTML, and has_element?/2 checks the DOM. Tests run as normal ExUnit tests.

ELIXIR
test "increments", %{conn: conn} do
  {:ok, view, _html} = live(conn, ~p"/counter")
  assert render_click(view, "increment") =~ "Count: 1"
end

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a connected LiveView page hold on the server?

    Each connected LiveView is an Elixir process whose state is the socket and its assigns.
  2. 2. Why does mount/3 run twice for a normal page visit?

    The first HTTP request renders full HTML; the websocket connection starts a new process that mounts again. Check connected?(socket) before subscribing or doing side effects.
  3. 3. What does LiveView send to the browser after an event?

    Static template parts are sent once. After that, only changed dynamic values travel, and the client patches the DOM.
  4. 4. Which callback receives a message sent with Phoenix.PubSub.broadcast/3?

    Broadcasts arrive as ordinary process messages, so they are handled by handle_info/2. handle_event/3 is for events from the browser.

Summary

  • A LiveView is a process: mount/3 sets assigns, handle_event/3 changes them, render/1 turns them into HEEx.
  • The first request is plain HTML; a websocket then connects and the page mounts again.
  • LiveView tracks assigns and sends only the changed dynamic parts.
  • Forms use to_form/1, phx-change and phx-submit with Ecto changesets.
  • PubSub plus handle_info/2 gives real-time updates to every open page.
  • Keep assigns small, validate every event, and move slow work out of handlers.

Next up: Releases, Config and Deployment.