Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 38 ยท LiveView

LiveView Streams, Navigation and JS Commands

Render big lists with LiveView streams, move between pages with patch and navigate, and run client-side effects with Phoenix.LiveView.JS commands.

Two questions come up as soon as a LiveView grows beyond a counter. How do you show a list with thousands of rows without keeping every row in server memory? And how do you move between pages without a full reload, while still keeping the URL meaningful? LiveView answers the first with streams and the second with patch and navigate. A third tool, Phoenix.LiveView.JS, lets you toggle menus and animate elements in the browser without a round trip.

Real Phoenix code is read-only on this site. The editors contain small JavaScript models so you can watch the rules play out.

Why streams

If you keep a list in an assign, the server must remember all of it. When one item changes, LiveView re-sends the whole list (change tracking works per assign, not per element). For a feed of 5,000 messages that is expensive in memory and bandwidth.

A stream flips this around. The server keeps nothing; it just sends instructions (insert this item, delete that one) and the browser keeps the DOM. After the render the stream is emptied.

ELIXIR
def mount(_params, _session, socket) do
  {:ok, stream(socket, :messages, Chat.list_messages())}
end

def handle_event("send", %{"text" => text}, socket) do
  {:ok, message} = Chat.create_message(text)
  {:noreply, stream_insert(socket, :messages, message, at: 0)}
end

def handle_event("remove", %{"id" => id}, socket) do
  message = Chat.get_message!(id)
  {:ok, _} = Chat.delete_message(message)
  {:noreply, stream_delete(socket, :messages, message)}
end

And the template must follow three rules: a container with an id and phx-update="stream", children iterated from @streams.messages, and each child given the dom id that the stream provides:

HTML
<ul id="messages" phx-update="stream">
  <li :for={{dom_id, message} <- @streams.messages} id={dom_id}>
    {message.text}
    <button phx-click="remove" phx-value-id={message.id}>x</button>
  </li>
</ul>

Useful options: stream_insert(..., at: 0) prepends (default appends at -1), stream(socket, :messages, items, reset: true) replaces the entire list (for filters or searches), and limit: 50 keeps only the newest items in the browser. By default the dom id is "messages-" <> id, built from the item's :id. If your structs have no id field, pass dom_id: fn item -> ... end.

Because a stream is emptied after rendering, you cannot count or filter its items on the server (@streams.messages is not a list you can Enum.count). Keep a separate assign for totals, or query the database.

A stream model

The stand-in below keeps a "browser DOM" separate from the "server". The server never stores the list after sending it; it only emits operations. Compare what travels to what the DOM holds.

Node.js Streams send operations, not lists (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.

LiveView has three ways to change the page, and the difference is what survives:

Move Template syntax Callback syntax What happens
Patch <.link patch={~p"/posts?page=2"}> push_patch(socket, to: ...) Same LiveView process; only handle_params/3 runs.
Navigate <.link navigate={~p"/posts/1"}> push_navigate(socket, to: ...) Different LiveView in the same live_session: old process stops, new one mounts, but the WebSocket stays.
Redirect <.link href={~p"/login"}> redirect(socket, to: ...) Full HTTP request and page load.

navigate only works between LiveViews in the same live_session (see the router below). Crossing a live_session boundary, for example from a public page to a logged-in one, forces a full redirect so that the new session's on_mount hooks run.

ELIXIR
scope "/", MyAppWeb do
  pipe_through [:browser, :require_authenticated_user]

  live_session :authenticated, on_mount: [{MyAppWeb.UserAuth, :ensure_authenticated}] do
    live "/posts", PostLive.Index, :index
    live "/posts/new", PostLive.Index, :new
    live "/posts/:id", PostLive.Show, :show
  end
end

The third argument (:index, :new) is the live action, available as @live_action. It lets one LiveView serve several URLs, such as a list page with a modal opened at /posts/new. The usual pattern is handle_params/3 that reads the URL and apply_action(socket, @live_action, params) that sets the assigns for that action.

Patching is perfect for state in the URL: current page, sort order, selected tab, search term. Users can then bookmark, reload and share the page, and the browser back button works.

Node.js Patch vs navigate (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.

JS commands

Not every interaction needs the server. Opening a dropdown or showing a modal is instant if the browser does it. Phoenix.LiveView.JS builds commands that LiveView runs on the client, and that are kept in place when the server re-renders (a plain JavaScript class toggle would be wiped out by the next diff).

ELIXIR
alias Phoenix.LiveView.JS

def toggle_menu(js \\ %JS{}) do
  js
  |> JS.toggle(to: "#menu", in: {"ease-out duration-200", "opacity-0", "opacity-100"})
  |> JS.toggle_attribute({"aria-expanded", "true", "false"}, to: "#menu-button")
end
HTML
<button id="menu-button" phx-click={toggle_menu()}>Menu</button>
<nav id="menu" class="hidden">...</nav>

<button phx-click={JS.push("archive", value: %{id: @post.id}) |> JS.hide(to: "#post-#{@post.id}")}>
  Archive
</button>

The most used commands are JS.show/1, JS.hide/1, JS.toggle/1, JS.add_class/2, JS.remove_class/2, JS.push/2 (send a server event), JS.navigate/2, JS.patch/2, JS.focus/1 and JS.dispatch/2 (fire a DOM event). Chain them with the pipe operator, as you know from the pipe operator. A command like JS.push(...) |> JS.hide(...) hides the element immediately and sends the event, giving an instant-feeling interface.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a LiveView stream keep on the server after the render?

    That is what makes streams memory-friendly. The server only emits insert and delete instructions.
  2. 2. Which attribute must the stream container have?

    The container needs an id and phx-update=stream; each child needs the dom id supplied by the stream.
  3. 3. You change ?page=2 in the URL while staying in the same LiveView. Which callback runs?

    A patch keeps the process alive and only calls handle_params/3.
  4. 4. Why use Phoenix.LiveView.JS instead of a plain JavaScript class toggle?

    LiveView DOM patching would overwrite manual changes; JS commands are tracked and re-applied.

Summary

  • Streams keep big lists out of server memory by sending insert, delete and reset operations.
  • Containers need id and phx-update="stream"; children use the stream's dom ids.
  • patch stays in the same process, navigate swaps LiveViews inside a live_session, redirect reloads.
  • Put filters, pages and tabs in the URL and read them in handle_params/3.
  • Phoenix.LiveView.JS runs client-side effects that survive re-renders.

Next: Live Components, Async Work and Hooks