DEV Community

Camilo
Camilo

Posted on • Updated on

LiveView vs LiveComponent vs Component

The official documentation says:

Some Context

  • handle_params: A function triggered in the parent LiveView with the url params.

  • mount: A function triggered in the parent LiveView and LiveComponents for setting the initial values.

  • update: A function triggered in the parent LiveView and LiveComponents for updating the assigns in a component instance.

  • preload: A function triggered in the parent LiveView and LiveComponents for updating the assigns in multiple instances of the component.

  • handle_event: A function triggered by the HTML/JS side.

  • handle_info: A function triggered by using send(self(), args) inside a live_component. Handled by the parent liveview.

  • pipeline: A function that is called when defining the live_view or live_component.

  • @myself: A target to specify in LiveViews or LiveComponents. phx-target={@myself}

lib/my_web/my_web.ex

def live_view do
    quote do
      use Phoenix.LiveView,
        layout: {MyWeb.Layouts, :app}

      unquote(html_helpers())
    end
end
Enter fullscreen mode Exit fullscreen mode

Used as

defmodule MyWeb.Live.Home do
  use MyWeb, :live_view
Enter fullscreen mode Exit fullscreen mode

This is how I understand the main differences

LiveView

  • Creates a socket
  • Handlers: handle_event, handle_info, handle_params, mount, update, preload.
  • Can use @myself to handle events (requires id)
  • Renders html

live_render/3

LiveComponent

  • Uses the socket defined in the Parent LiveView
  • Handlers: handle_event,mount, update, preload.
  • Can use @myself to handle events (requires id)
  • Renders html
<.live_component module={MyModule} id="unique_id" {assigns} />
Enter fullscreen mode Exit fullscreen mode

Component

  • Only renders html
<MyComponent.render {assigns} />
Enter fullscreen mode Exit fullscreen mode

Comparison

Item LiveView LiveComponent Component
renders html
can use @myself (requires id)
mount
update
preload
handle_event
handle_info
handle_params
creates a socket

Top comments (0)