liveview

LiveView

Specific best practices and architectural patterns when working with LiveView.

Details

Language / Topic
elixirElixir
Category
framework

Rules

balanced

Phoenix LiveView

- Keep LiveView modules focused on UI concerns — delegate business logic to context modules, not handle_event callbacks.
- Use `assign/2` and `assign_new/3` to manage socket assigns — never store derived data that can be computed from existing assigns.
- Use `live_component/1` to break large LiveViews into reusable, independently updatable components with their own lifecycle.

Phoenix LiveView

- Keep LiveView modules focused on UI concerns — delegate business logic to context modules. The `handle_event/3` callback should validate input and call a context function, not contain domain logic.
- Use `assign/2` and `assign_new/3` to manage socket assigns — never store derived data that can be computed. Compute derived values in the template or a helper.
- Use `live_component/1` to decompose large LiveViews into reusable, independently updatable components with their own `update/2` and `handle_event/3` callbacks.
- Minimize data sent over the WebSocket — assign only the data the template needs. Use `temporary_assigns` for large lists that don't need to persist in memory after render.
- Handle all expected disconnect/reconnect scenarios — LiveView will remount on reconnect, so `mount/3` must be idempotent and restore state correctly.
- Use `push_event/3` for server-to-client communication and JavaScript hooks (`phx-hook`) for integrating third-party JS libraries — keep JS minimal.
- Use `stream/3` for large or paginated collections — streams efficiently manage DOM updates without keeping the full collection in socket assigns.