DEV Community

Camilo
Camilo

Posted on • Edited on

15 2 2 1

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

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay