Phoenix LiveView: mount, assigns & Events
LiveView builds rich, real-time interactive UIs mostly in server-side Elixir. State lives on the server; after an initial server-rendered HTML response, a persistent WebSocket connection lets LiveView push only minimal DOM diffs on each state change.
A Basic LiveView
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, assign(socket, :count, socket.assigns.count + 1)}
end
def render(assigns) do
~H"""
<p>Count: <%= @count %></p>
<button phx-click="increment">+1</button>
"""
end
endThe First Request: Real HTML, No JS Required
On the initial HTTP request, LiveView server-renders a fully-formed HTML page -- content is visible immediately, good for SEO and perceived load time. The WebSocket then connects to enable further interactivity.
Minimal Diffs, Not Full Re-Renders
LiveView's compiler knows which parts of a template are static and which depend on specific assigns. On a state change, only the genuinely changed dynamic parts are sent over the socket -- not the whole page.
Live Form Validation
def handle_event("validate", %{"user" => params}, socket) do
changeset = User.changeset(%User{}, params) |> Map.put(:action, :validate)
{:noreply, assign(socket, :changeset, changeset)}
end
# phx-change="validate" on the <form> sends input as the user
# types, letting real Ecto changeset validation run live server-sideKeep your own version of these notes — editable, searchable, and organised by your stack.
Start free