Advanced

Lazy Loading

React.lazy and Suspense inside LiveView

  • dead view
  • React.lazy
  • Suspense

Key concepts

React.lazy wraps a dynamic import(), so the wrapped module is fetched as its own chunk only when it is first rendered, and Suspense renders a fallback while that chunk loads. Nothing about this is specific to LiveReact — it is ordinary React code splitting, running inside a Phoenix-rendered page.

page_html.ex
defmodule MyAppWeb.PageHTML do
  use MyAppWeb, :html

  def lazy(assigns) do
    ~H"""
    <.react name="Lazy" />
    """
  end
end

How it works

The build tool splits the lazily imported component into its own bundle at build time. In this demo the chunk loads too fast to see the fallback, but the network tab shows a separate request for it, made only once Lazy renders — not on first page load.