A detailed pattern for building self-contained, stateful widgets in Phoenix LiveView using attach_hook/4, function components, and plain structs stored in socket.assigns. The approach solves limitations of LiveComponents (no handle_info, no handle_params) and embedded LiveViews (separate processes, string-only session). Each widget module encapsulates a state struct, an assign_component/n setup function, a pure render/1 function component, and optional hook callbacks for events, PubSub messages, and URL params. A full chat widget example demonstrates event namespacing, multi-instance support via assign keys, PubSub integration, URL-driven state, and a memory trade-off with LiveView streams. The parent LiveView needs only two lines to mount and render the widget.

17m read timeFrom curiosum.com
Post cover image
Table of contents
1. State: The Struct2. Pure Rendering3. Mounting4. Hook Attachment5. Terminating6. Event Handling: Sending Chat Messages7. Real-time Updates: PubSub Messages8. URL Params: Chat Room9. Stream IntegrationTrade-off: Stream PruningThe Fix: Separate Stream from State

Sort: