Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 38 ยท LiveView

LiveView Lifecycle: Mount, Render and Assigns

Learn how a Phoenix LiveView starts: the two mounts, connected?/1, assigns, handle_params/3, the ~H template and how change tracking sends tiny diffs.

A controller handles one request and is done. A LiveView is different: it is a long-lived Elixir process that stays alive for as long as the browser tab is open. It keeps its state in a struct called the socket, renders HTML from that state, and when something happens it re-renders and sends only what changed. Understanding the order in which things happen is the key to every LiveView bug you will ever debug.

Real Phoenix cannot run on this site, so the Elixir blocks are read-only and copied from how a normal Phoenix 1.8 project looks. The editors use a JavaScript stand-in that imitates the lifecycle and the diff idea. I will say which parts are real and which are simplified. If you have not met processes yet, read Processes and Messages and the short LiveView introduction first.

A minimal LiveView

A LiveView is a module that uses the web module's :live_view helper and implements mount/3, render/1 and event callbacks:

ELIXIR
defmodule MyAppWeb.CounterLive do
  use MyAppWeb, :live_view

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

  def render(assigns) do
    ~H"""
    <Layouts.app flash={@flash}>
      <p>Count: {@count}</p>
      <button phx-click="inc">+1</button>
    </Layouts.app>
    """
  end

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

You mount it from the router with one line, in a scope that pipes through the browser pipeline:

ELIXIR
live "/counter", CounterLive

Three things to notice. assign/2 returns a new socket, because data in Elixir is immutable. {@count} inside ~H reads the assign called count. And handle_event/3 returns {:noreply, socket}; there is no explicit "send HTML" step, because the process re-renders automatically when assigns change.

The two mounts

A LiveView is rendered twice for a page load:

  1. Disconnected render. The browser asks for /counter over plain HTTP. Phoenix runs mount/3 and render/1, and returns normal HTML. This is fast, indexable by search engines and works without JavaScript.
  2. Connected render. The page loads the LiveView JavaScript, which opens a WebSocket. Phoenix starts a new process, runs mount/3 again, renders again, and keeps the process alive.
sequenceDiagram
    participant B as Browser
    participant S as Phoenix
    B->>S: GET /counter (HTTP)
    S->>S: mount (disconnected) + render
    S-->>B: Full HTML page
    B->>S: WebSocket connect
    S->>S: new process: mount (connected) + render
    S-->>B: Rendered state, then small diffs

A page load runs mount twice: once for the HTTP response and once when the socket connects.

This is why mount/3 must be cheap and free of side effects that you do not want twice. Subscribing to a topic, starting a timer or opening a stream should happen only in the connected mount. Phoenix gives you the check:

ELIXIR
def mount(_params, _session, socket) do
  if connected?(socket) do
    Phoenix.PubSub.subscribe(MyApp.PubSub, "orders")
    :timer.send_interval(1000, self(), :tick)
  end

  {:ok, assign(socket, orders: list_orders(), now: DateTime.utc_now())}
end

connected?/1 is false during the HTTP render and true in the process that owns the WebSocket. Loading data from the database in mount/3 still runs twice; that is normal, and later lessons show assign_async for slow work.

Params, session and handle_params

mount/3 receives the URL params, the session (what was stored in the cookie, such as a user token) and the socket. When the URL changes without leaving the LiveView (for example ?page=2), Phoenix does not mount again. It calls handle_params/3:

ELIXIR
def mount(_params, _session, socket) do
  {:ok, assign(socket, :page, 1)}
end

def handle_params(%{"page" => page}, _uri, socket) do
  {:noreply, assign(socket, :page, String.to_integer(page))}
end

def handle_params(_params, _uri, socket), do: {:noreply, socket}

Treat handle_params/3 as the place that turns the URL into assigns. mount/3 sets defaults and subscribes. That split keeps pages bookmarkable and makes the back button work, which the next lessons use for navigation.

Assigns and change tracking

All state lives in socket.assigns. Helpers you will use daily:

Function What it does
assign(socket, key: value) Set one or more assigns
assign_new(socket, :key, fn -> ... end) Set only if missing (skips work already done)
update(socket, :key, fun) Compute the new value from the old
socket.assigns.key Read an assign in callbacks

The magic is change tracking. The ~H template is compiled into a list of static strings and a list of dynamic expressions. After an event, LiveView re-evaluates only the expressions whose assigns changed and sends just those values. A button press that bumps one number sends a few bytes, not the whole page. Two rules follow from it:

  • Reference assigns directly (@count), not through a big nested map you rebuild each time, or everything counts as changed.
  • Never put an assign into the socket that you do not render or use; large unused data only costs memory in the process.

A runnable model

The first stand-in is a tiny LiveView runtime in JavaScript. It has the same shape as the real thing: mount, render split into statics and dynamics, and a diff that sends only the dynamics whose values changed.

Node.js A tiny LiveView runtime (stand-in)

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The statics (the unchanging HTML) travel only once, on the first render. Every later message carries only the changed positions, which is exactly why LiveView updates stay small even for big pages.

Why mount runs twice, in code

Counting runs makes the double mount concrete. The next stand-in simulates a page load and shows that a naive mount that increments a database counter would count every visit twice, while a connected? guard counts once.

Node.js Why connected? matters (stand-in)

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Common mistakes

  • Side effects in mount/3 without connected?/1. Emails, counters and subscriptions run twice.
  • Heavy queries in both mounts. Load only what the first paint needs; use async assigns for the rest.
  • Mutating "state" in a module attribute or ETS by accident. The state of a LiveView is its socket, per user and per tab.
  • Forgetting {:noreply, socket}. Every handle_event/3 must return a tuple, not a bare socket.

When something looks wrong, open the browser DevTools Network tab, filter by WS, and watch the diffs. You will see exactly which parts the server sent.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many times does mount/3 run for a first page load of a LiveView?

    Phoenix renders the page over HTTP first for speed and SEO, then starts a stateful process on connect and mounts again.
  2. 2. Where should you subscribe to a PubSub topic?

    Subscriptions belong to the long-lived process, so they must be created only in the connected mount.
  3. 3. What does change tracking send after an event?

    The static parts of the template are sent once; later updates carry just the changed dynamic parts.
  4. 4. Which callback turns URL parameters into assigns when the URL changes inside the same LiveView?

    handle_params/3 runs after mount and on every patch of the URL, so state derived from the URL stays in sync.

Summary

  • A LiveView is a process whose state is the socket's assigns.
  • mount/3 runs twice per page load; guard side effects with connected?/1.
  • handle_params/3 converts the URL into state and runs on every patch.
  • ~H templates are split into statics and dynamics, so updates send small diffs.
  • assign, assign_new and update return a new socket; always return {:noreply, socket}.

Next: LiveView Events and Forms