jtormey

jtormey

I’m sure some of you have experienced this as well, in a growing LiveView application it can become difficult to trace flow of data between a LiveView and child components that communicate via send/2 / handle_info/2.

Typically, it looks like this:

# In AppWeb.ParentLive

def render(assigns) do
  ~H"""
  <.live_component id="child" module={AppWeb.ChildComponent} />
  """
end

def handle_info({:from_child, data}, socket) do
  # Handle message from child
end

# In AppWeb.ChildComponent

def handle_event("some_event", _params, socket) do
  send(self(), {:from_child, %{some: :data}})
  {:noreply, socket}
end

With many children each sending multiple messages to a parent, you can see how this might make navigating code confusing.

Now, what if we could simply pass functions defined in the parent LiveView to children, like how is typically done in React? The reason we “can’t” do this is because we need access to socket… but there’s nothing stopping us from hiding implementation details with a macro.

Take this counter example using a defcall macro (shown at the end of the post):

defmodule AppWeb.CounterLive do
  use AppWeb, :live_view

  import Defcall

  def mount(_params, _session, socket) do
    {:ok, assign(socket, :count, 0)}
  end

  def render(assigns) do
    ~H"""
    <.live_component
      id="counter"
      module={__MODULE__.Counter}
      count={@count}
      on_inc={&inc/1}
      on_dec={&dec/1}
    />
    """
  end

  defcall inc(by_value, socket) do
    count = socket.assigns.count
    {:noreply, assign(socket, :count, count + by_value)}
  end

  defcall dec(by_value, socket) do
    count = socket.assigns.count
    {:noreply, assign(socket, :count, count - by_value)}
  end

  defmodule Counter do
    use AppWeb, :live_component

    def render(assigns) do
      ~H"""
      <div>
        Count: <%= @count %>
        <button phx-click="inc" phx-target={@myself}>Increment</button>
        <button phx-click="dec" phx-target={@myself}>Decrement</button>
      </div>
      """
    end

    def handle_event("inc", _params, socket) do
      socket.assigns.on_inc.(1)
      {:noreply, socket}
    end

    def handle_event("dec", _params, socket) do
      socket.assigns.on_dec.(1)
      {:noreply, socket}
    end
  end
end

Neat! Now, we can define functions in our parent and pass them to child components. It looks like they’re being called directly, but in reality we’re using the same message passing technique as before behind the scenes.

Here’s the full macro code for reference:

defmodule Defcall do
  @doc """
  This:

  defcall inc(by_value, socket) do
    count = socket.assigns.count
    {:noreply, assign(socket, :count, count + by_value)}
  end

  Becomes this:

  def inc(by_value) do
    send(self(), {:__prop_callback__, :inc, [by_value]})
  end

  def handle_info({:__prop_callback__, :inc, [by_value]}, socket) do
    count = socket.assigns.count
    {:noreply, assign(socket, :count, count + by_value)}
  end
  """
  defmacro defcall(fn_spec, do: block) do
    {fn_name, _, args} = fn_spec

    # Drop the socket arg, should add some error handling here
    args = Enum.drop(args, -1)

    quote location: :keep do
      def unquote(fn_name)(unquote_splicing(args)) do
        send(self(), {:__prop_callback__, unquote(fn_name), [unquote_splicing(args)]})
      end

      def handle_info(
            {:__prop_callback__, unquote(fn_name), [unquote_splicing(args)]},
            var!(socket)
          ) do
        unquote(block)
      end
    end
  end
end

Anyway, just wanted to share and hear if anyone had thoughts on a system like this. And even if it’s flawed somehow, it’s amazing how easy it is to expand our tools using the language constructs available to us.

How else have you organized messaging between components?

Showing Posts 1 to 3

cmo

cmo

I namespace them, e.g "component:message" or {Component, :message}.

TwistingTwists

TwistingTwists

Just like live_beats app does :rofl:

cmo

cmo

Pretty sure they copied it from my closed source app :thinking:

— All posts loaded —

Where Next? Top

Trending in Discussions Top

AstonJ
As the title says, please share what you’ve been up to with Elixir. Whether that’s been learning it, looking into it, making stuff with i...
2977 94592 917
New
cblavier
Hey there, It’s been more than a year since we started using LiveView as our main UI library and building a whole library of UI componen...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
heathen
Quite interesting article Google brought me. Didn’t find any mentions about it here. What do you think in general? Would you use togethe...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
axelson
Hi there! :wave: @frigidcode and I (but mostly him) have been running an Elixir Book club, we’re almost done with Designing Elixir Syste...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
georgeguimaraes
Just published claude-code-elixir, a plugin marketplace for Claude Code with Elixir support. These are the plugins I’ve been using for my...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews