Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 38 ยท LiveView

Live Components, Async Work and Hooks

Split LiveView into function components and stateful LiveComponents, load slow data with assign_async and start_async, and bridge to JavaScript with hooks.

As a LiveView page grows, three problems appear. The template becomes huge, some pieces need their own state and events, and some data is slow to load and should not block the first paint. Phoenix gives each problem a tool: function components for reusable markup, LiveComponents for stateful pieces, and async assigns for slow work. When you need a browser-only library, such as a chart or a map, you add a client hook.

Everything here is real Phoenix 1.8 / LiveView 1.1 style code in read-only blocks, with JavaScript stand-ins that you can run to see how the ideas behave.

Function components first

A function component is a plain function that takes assigns and returns a ~H template. It has no state and no process. You already use many: <.input>, <.button>, <.link>.

ELIXIR
attr :status, :atom, required: true, values: [:draft, :published]
slot :inner_block, required: true

def badge(assigns) do
  ~H"""
  <span class={["badge", @status == :published && "badge-success"]}>
    {render_slot(@inner_block)}
  </span>
  """
end

attr and slot declare the API; the compiler warns when a caller passes an unknown attribute or forgets a required one. Use them for 90% of reuse. The next two tools are for the remaining cases.

LiveComponent: a stateful piece

A LiveComponent lives inside its parent LiveView's process but has its own assigns and its own handle_event/3. Use it when a part of the page has state that the rest should not care about, such as an inline editor or a comment box.

ELIXIR
defmodule MyAppWeb.CommentFormComponent do
  use MyAppWeb, :live_component

  def update(%{post: post} = assigns, socket) do
    {:ok,
     socket
     |> assign(assigns)
     |> assign(:form, to_form(Blog.change_comment(%Blog.Comment{post_id: post.id})))}
  end

  def render(assigns) do
    ~H"""
    <div>
      <.form for={@form} phx-submit="save" phx-target={@myself} id={"comment-form-#{@id}"}>
        <.input field={@form[:body]} label="Comment" />
        <.button>Post</.button>
      </.form>
    </div>
    """
  end

  def handle_event("save", %{"comment" => params}, socket) do
    case Blog.create_comment(socket.assigns.post, params) do
      {:ok, comment} ->
        send(self(), {:comment_created, comment})
        {:noreply, assign(socket, :form, to_form(Blog.change_comment(%Blog.Comment{})))}

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

Rendering it from the parent:

HTML
<.live_component module={MyAppWeb.CommentFormComponent} id="new-comment" post={@post} />

Key rules:

  • A LiveComponent needs a unique id. That id is its identity; without it, it would not be stateful.
  • Events go to the parent unless you add phx-target={@myself}. Forgetting phx-target is the number one source of "my component ignores clicks" questions.
  • update/2 receives the assigns from the parent each time it renders, and mount/1 runs once.
  • Talk upward with send(self(), message), which the parent handles in handle_info/2 (the LiveComponent shares the parent's process, so self() is the parent). Talk downward with send_update(MyAppWeb.CommentFormComponent, id: "new-comment", ...).

Prefer function components, then a LiveComponent only if you need local state or targeted events. Many apps never need more than a handful.

Node.js phx-target: who receives the event? (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.

Async work: assign_async and start_async

Imagine a dashboard whose "revenue" query takes two seconds. If you run it in mount/3, the page appears two seconds late. assign_async/3 runs a function in a separate process and assigns the result when it is ready, so the page renders instantly with a loading state:

ELIXIR
def mount(_params, _session, socket) do
  {:ok,
   socket
   |> assign(:page_title, "Dashboard")
   |> assign_async(:revenue, fn -> {:ok, %{revenue: Reports.revenue_this_month()}} end)}
end
HTML
<.async_result :let={revenue} assign={@revenue}>
  <:loading>Loading revenue...</:loading>
  <:failed :let={_reason}>Could not load revenue.</:failed>
  ${revenue}
</.async_result>

The function must return {:ok, %{assign_name: value}} or {:error, reason}. The assign holds an AsyncResult struct with states loading, ok and failed, and <.async_result> renders the right slot. A crash inside the function becomes the failed state; it does not take the LiveView down.

For work triggered by an event, use start_async/3 with a handle_async/3 callback:

ELIXIR
def handle_event("export", _params, socket) do
  {:noreply, start_async(socket, :export, fn -> Reports.build_csv() end)}
end

def handle_async(:export, {:ok, csv}, socket), do: {:noreply, assign(socket, :csv, csv)}
def handle_async(:export, {:exit, reason}, socket), do: {:noreply, put_flash(socket, :error, "Export failed: #{inspect(reason)}")}

Under the hood these are tasks linked to the LiveView; if the user leaves the page the task is cancelled.

Node.js Async assigns with a loading state (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.

Client hooks

Sometimes you need JavaScript: a chart library, a drag handle, the clipboard. A hook attaches a JavaScript object to an element with phx-hook, with callbacks that run when the element is added, updated and removed.

HTML
<canvas id="sales-chart" phx-hook="Chart" phx-update="ignore" data-points={Jason.encode!(@points)}></canvas>
JavaScript
// assets/js/app.js
const Hooks = {
  Chart: {
    mounted() {
      this.chart = drawChart(this.el, JSON.parse(this.el.dataset.points));
      this.handleEvent("points", ({ points }) => this.chart.update(points));
      this.el.addEventListener("click", () => this.pushEvent("chart-clicked", {}));
    },
    updated() { /* the element's attributes changed */ },
    destroyed() { this.chart.destroy(); },
  },
};
const liveSocket = new LiveSocket("/live", Socket, { hooks: Hooks, params: { _csrf_token: csrfToken } });

On the server, push_event(socket, "points", %{points: new_points}) sends data to handleEvent, and this.pushEvent("chart-clicked", ...) triggers handle_event/3 going the other way. A hooked element must have a unique id, and phx-update="ignore" tells LiveView not to overwrite DOM that the library manages.

Other common needs have built-in support: file uploads with allow_upload/3, <.live_file_input> and consume_uploaded_entries/3 (with progress and direct-to-cloud uploads), and <.live_title> for the page title.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When should you choose a LiveComponent over a function component?

    Function components are stateless and cover most reuse. A LiveComponent is for self-contained state.
  2. 2. A button inside a LiveComponent does nothing when clicked. What is the most likely cause?

    Without phx-target, events are delivered to the parent LiveView, which has no matching clause.
  3. 3. What does assign_async/3 do if the function crashes?

    The work runs in a separate task; a failure becomes the failed state that <.async_result> can render.
  4. 4. What must an element with phx-hook always have?

    LiveView tracks hooks by DOM id, so each hooked element needs one that is unique on the page.

Summary

  • Prefer function components with attr and slot; they are stateless and cheap.
  • A LiveComponent has its own state, needs an id, and receives events only with phx-target={@myself}.
  • assign_async/3 and start_async/3 keep slow queries out of the critical path and isolate failures.
  • Hooks bridge to JavaScript: mounted, updated, destroyed, pushEvent, handleEvent.

Next: Channels and Sockets