Jeffrey Hicks

Jeffrey Hicks

Platform Eng @R360

19 - Phoenix crash course #19: LiveView

Learn how to build interactive, real-time UIs with Phoenix LiveView using minimal JavaScript

By Daniel Bergholz • Aug 19, 2025

Learn how to build interactive, real-time UIs with Phoenix LiveView using minimal JavaScript.

What is LiveView?

Phoenix LiveView lets you build rich, interactive, real-time UIs with minimal JavaScript—most interactivity comes from the Elixir backend over a single persistent WebSocket.

How does it differ from React?

React runs in the browser and updates UI with JS.
LiveView runs most UI logic on the server, sending DOM diffs over a socket—browser just patches DOM; state is held on the server.

Creating a LiveView

  • In router.ex, use live "/products-live", ProductLive.Index
  • Create a module (e.g., ShopWeb.ProductLive.Index) using use ShopWeb, :live_view
  • Implement mount/3 (like React’s useEffect on mount): fetch data, assign state
  • Implement render/1 using HEEx (& the ~H sigil) for HTML
  • Data (e.g., list of products) is assigned to the socket and available to the template

Components and state

  • Uses Phoenix built-in Heroicons for icons
  • Track local state (e.g., likes per product) using assigns—a map, typically product ID to likes count
  • Handle interactive events with handle_event/3 (e.g., “like”, “dislike”), mutate assigns, and update UI via socket assign
  • Use PHX attributes (phx-click, phx-value-*) to trigger server events and pass data from the client

Testing LiveView

  • Use phoenix_live_view_test helpers like live/2, render_click/3 in your test modules
  • Test interactive events (like/dislike) by simulating client events and asserting on updated HTML

Debugging and Dev

  • Inspect the socket/WebSocket tab in browser devtools to see payloads
  • Simulate latency using liveSocket.enableLatencySim(ms) in the browser console to see effect of geographic distances

Tips

  • PHX attributes allow for rich interactivity: phx-click, phx-blur, phx-focus, phx-submit, phx-change, etc.—hook user events directly to Elixir handlers
  • For client-only state, stick to JS or React; for backend-driven UI or sync between users, favor LiveView for a better balance of performance and simplicity

Resources

Summary

Phoenix LiveView empowers you to build server-driven, reactive UIs—with little JS and mucho Elixir. It unifies complex frontend interactivity with testable Elixir code, featuring built-in event handling, flexible state, and developer aides for rapid feedback and robust test suites.

Related

#phoenix-and-elixir #phoenix-crash-course #daniel-bergholz