Events

Server Events

push_event on the server reaches handleEvent in React

  • push_event
  • handleEvent
  • toasts

Key concepts

push_event/3 sends a one-off message from the server straight to the client — it is not a prop and does not go through a diff. React picks it up with handleEvent, registered once via useEffect.

server_events_live.ex
defmodule MyAppWeb.ServerEventsLive do
  use MyAppWeb, :live_view

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

  def render(assigns) do
    ~H"""
    <div class="flex gap-2">
      <.button phx-click="info">info</.button>
      <.button phx-click="error">error</.button>
    </div>
    <.react name="ServerEvents" socket={@socket} />
    """
  end

  def handle_event("info", _params, socket) do
    {:noreply, push_event(socket, "info", %{message: "This is an info message"})}
  end

  def handle_event("error", _params, socket) do
    {:noreply, push_event(socket, "error", %{message: "This is an error message"})}
  end
end

How it works

Clicking a button is an ordinary phx-click, handled by handle_event/3 on the server exactly as it would be outside LiveReact. Instead of reassigning a prop, the handler calls push_event/3 with an event name and a payload map.

On the client, handleEvent("info", callback) fires that callback the moment the event arrives, independently of any render — this is how a server-driven toast, a sound, or a one-shot animation reaches React without being modeled as state.