Skip to content
Skills Library
Programming · Building & coding

liveview-patterns

/liveview-patterns

Build LiveView: async data (assign_async), PubSub (check connected?); Use when handling interactions, debugging…

Licence
MIT
Last repository change
22.10.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
7
Scripts
0
HTML comments
0
URLs in SKILL.md
0
Deprecation

No signals detected. Repository changed on 22.10.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

Build LiveView: async data (assign_async), PubSub (check connected?); Use when handling interactions, debugging…

Original author description

Build LiveView: async data (assign_async), PubSub (check connected?); Use when handling interactions, debugging…

How it works

  1. Iron Laws — Never Violate These
  2. Memory Impact
  3. Quick Patterns
  4. Navigation Decision Tree
  5. Component Decision Tree
  6. Common Anti-patterns
  7. References
Original SKILL.md headings · 129 lines, 649 words
SKILL.md preview
---
name: liveview-patterns
description: 'Build LiveView: async data (assign_async), PubSub (check connected?);
  Use when handling interactions, debugging…'
---

# LiveView Patterns Reference

> **Ash projects**: Use `ash-framework` skill for `AshPhoenix.Form`. Lifecycle: `AshPhoenix.Form.validate/3` on `phx-change`, `AshPhoenix.Form.submit/2` on submit, `to_form/1` for HEEx. Do not use `Ecto.Changeset.cast/3`.

Reference for building with Phoenix LiveView 1.0/1.1.

## Iron Laws — Never Violate These

1. **NO UNCONDITIONAL DB QUERIES IN MOUNT** — Mount runs TWICE. Default: `assign_async`. SEO routes: `connected?` guard + cache-backed disconnected branch (crawlers read that HTML)
2. **ALWAYS USE STREAMS FOR LISTS** — Regular assigns = O(n) memory per user. Streams = O(1)
3. **CHECK connected?/1 BEFORE SUBSCRIPTIONS** — Prevents double subscriptions
4. **EXTRACT VARIABLES BEFORE assign_async CLOSURE** — Closures copy entire referenced variables
5. **LOAD PRIMARY DATA IN mount/3, PAGINATION IN handle_params/3** — handle_params runs on EVERY URL change
6. **NEVER PASS SOCKET TO BUSINESS LOGIC** — Extract data before calling contexts
7. **CHECK CHANGESET ERRORS BEFORE UI DEBUGGING** — Silent form save = check `{:error, changeset}` first, not viewport/JS
8. **HIDDEN INPUTS FOR ALL REQUIRED EMBEDDED FIELDS** — Every required field in an embedded schema MUST have a `hidden_input` if not directly editable
9. **NEVER USE `assign_new` FOR LIFECYCLE VALUES** — `assign_new` skips the function if key exists. Use `assign/3` for locale, current user, or any value refreshed every mount
10. **MATCH `{:error, %Ecto.Changeset{}}` EXPLICITLY** — Bare `{:error, _}` merges changeset and non-changeset errors; the form silently never re-renders validation errors. Handle other errors separately

## Memory Impact

| Pattern | 3K items | 10K users × 10K items |
|---------|----------|----------------------|
| Regular assigns | ~5.1 MB | ~10+ GB |
| Streams | ~1.1 MB | Minimal (O(1)) |

**Decision**: Lists with >100 items → Use streams, not assigns

## Quick Patterns

### Async Assigns (CRITICAL)

```elixir
def mount(%{"slug" => slug}, _session, socket) do
  # Extract needed values BEFORE the closure
  scope = socket.assigns.current_scope

  {:ok,
   socket
   |> assign_async(:org, fn -> {:ok, %{org: fetch_org(scope, slug)}} end)}
end
```

### Streams for Lists

```elixir
def mount(_params, _session, socket) do
  {:ok, stream(socket, :items, Items.list_items())}
end

# Insert/update/delete
stream_insert(socket, :items, item, at: 0)
stream_delete(socket, :items, item)
```

### SEO Dead-Render (cache-backed disconnected branch)

For public/SEO-visible routes (marketing, articles, product listings) the
disconnected render IS the HTML crawlers see. Fetch from a cache there, real
data on connect:

```elixir
def mount(_params, _session, socket) do
  products =
    if connected?(socket),
      do: Catalog.list_products(),
      else: Cache.get_products() || []

  {:ok, assign(socket, products: products)}
end
```

Empty list → `<noscript>`-friendly skeleton. Cache → `:persistent_term`, ETS,
or Cachex. This satisfies Iron Law #1 AND keeps Googlebot/GPTBot happy.

### PubSub with connected? check

```elixir
def mount(_params, _session, socket) do
  if connected?(socket), do: Chat.subscribe(room_id)
  {:ok, socket}
end
```

## Navigation Decision Tree

```
Same LiveView, different params? → patch / push_patch
Different LiveView, same live_session? → navigate / push_navigate
Different live_session or non-LiveView? → href / redirect
```

## Component Decision Tree

```
Does component need BOTH internal state AND event handling?
│
├── YES → Does it encapsulate APPLICATION logic (not just DOM)?
│   ├── YES → Use LiveComponent ✅
│   └── NO → Refactor to function component with parent handling
│
└── NO → Use Function Component ✅
```

**Official guidance**: "Prefer function components over live components"

## Common Anti-patterns

| Wrong | Right |
|-------|-------|
| DB queries without `assign_async` | Use `assign_async` for mount queries (SEO routes: `connected?` + cached dead render) |
| `assign(socket, items: list)` for lists | `stream(socket, :items, list)` |
| PubSub subscribe without `connected?` | `if connected?(socket), do: subscribe()` |
| Passing socket to context functions | Extract `socket.assigns` first |
| Business logic in `handle_event` | Delegate to context |
| `assign_new` for locale/user in hooks | `assign/3` (must run every mount) |

## References

For detailed patterns, see:

- `references/async-streams.md` - assign_async, stream_async, streams
- `references/forms-uploads.md` - Forms, validation, file uploads
- `references/components.md` - Function components, LiveComponents
- `references/pubsub-navigation.md` - PubSub, navigation, JS commands
- `references/js-interop.md` - Third-party JS libraries, phx-update="ignore", hooks
- `references/channels-presence.md` - Phoenix Channels, Presence, token auth
Files in this package (7)
  • SKILL.md 5 KB
  • references/async-streams.md 6 KB
  • references/channels-presence.md 5 KB
  • references/components.md 3 KB
  • references/forms-uploads.md 3 KB
  • references/js-interop.md 8 KB
  • references/pubsub-navigation.md 5 KB

Versions

RepositoryScoreLicence
This page · oliver-kriska/claude-elixir-phoenix100MIT
oliver-kriska/claude-elixir-phoenix100MIT

Identical content appears in 1 other GitHub folders. We show one copy with the highest score.

Database snapshot: 13.11.2026 · package version ff045da6e734 (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 100phoenix-pubsub-patterns
    Use when adding real-time updates to LiveViews with Phoenix.PubSub — scoped topics, broadcasting from contexts, handle_info with streams, Presence in LiveView. Not for raw WebSocket APIs (use phoenix-channels-essentials).
  • 100phoenix
    Build and debug Phoenix web interfaces and HTTP endpoints. Use for LiveView lifecycle and data loading, components, forms, routes, controllers, Plug, channels, and PubSub. Use ecto for changesets, queries, and persistence behind those interfaces.
  • 100liveview-code-review
    Reviews Phoenix LiveView code for lifecycle patterns, assigns/streams usage, components, and security. Use when reviewing LiveView modules, .heex templates, or LiveComponents.
  • 100phoenix
    Use when building an Elixir web app with Phoenix — contexts, Ecto schemas, changesets and migrations, LiveView, channels and PubSub, the generators, and the boundary between domain logic and the web layer. Covers the classic LiveView over-rendering and Ecto N+1 traps. NOT pure…
  • 100phoenix-thinking
    This skill should be used when the user asks to "add a LiveView page", "create a form", "handle real-time updates", "broadcast changes to users", "add a new route", "create an API endpoint", "fix this LiveView bug", "why is mount called twice?", or mentions handle_event,…
  • 100estack-liveview
    Build Phoenix LiveView forms, streams, components, hooks, and authenticated screens. Use when editing HEEx, LiveView events, UI styling, live_session, or asynchronous UI work.

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.