Good idea: A LiveView with local function components?

I have some LiveViews with some very long render templates. To aid modularity and readability, I’ve experimented with moving portions of the templates into function components. For example:

defmodule MyAppWeb.TestLive do
  use MyAppWeb, :live_view

  def mount(_params, _session, socket) do
    {:ok, assign(socket, name: "John Doe", message: "Hello")}
  end

  def render(assigns) do
    ~H"""
    <.my_header name={@name}/>
    <.my_body message={@message} />
    """
  end

  def my_body(assigns) do
    ~H"""
    <p><%= @message %></p>
    """
  end

  def my_header(assigns) do
    ~H"""
    <h1><%= @name %></h1>
    """
  end
end

Can anyone see anything wrong with this approach?

Nope, I do this a fair bit!

3 Likes

Good to hear that others are doing this as well.

One thing I wondered about was whether LiveView would be able to send data diffs to the browser as efficiently, since I’m a little vague on how that all works.

2 Likes

Yes it does. But You can see what is passing in the network tab of browser dev tools

Perfectly valid method. It’s done in core_components too.

Link

1 Like

I’ve been using this technique for a while now and I can’t imagine not using it going forward. I wonder if this practice is documented anywhere, since I hadn’t come across it. In my opinion, it ought to be documented.