Components

Azu's live components enable real-time UI updates through WebSocket connections. These components automatically sync with the server and update the DOM in real-time, providing a seamless interactive experience.

Overview

Live components provide:

  • Real-time DOM updates without page refreshes

  • Server-side state management with client synchronization

  • Event-driven interactions with immediate feedback

  • Component lifecycle management for proper cleanup

  • Type-safe event handling with Crystal's type system

Architecture

spinner

Basic Live Component

Simple Counter Component

class CounterComponent < Azu::Component
  def initialize(@initial_count : Int32 = 0)
    @count = @initial_count
  end

  def content
    div class: "counter", id: "counter-#{object_id}" do
      h3 "Counter"
      span id: "count", class: "count" do
        text @count.to_s
      end

      div class: "controls" do
        button onclick: "increment()", class: "btn btn-primary" do
          text "Increment"
        end
        button onclick: "decrement()", class: "btn btn-secondary" do
          text "Decrement"
        end
        button onclick: "reset()", class: "btn btn-danger" do
          text "Reset"
        end
      end
    end
  end

  def on_event("increment", data)
    @count += 1
    update_element "count", @count.to_s
  end

  def on_event("decrement", data)
    @count -= 1
    update_element "count", @count.to_s
  end

  def on_event("reset", data)
    @count = @initial_count
    update_element "count", @count.to_s
  end
end

Using the Component

Component Lifecycle

Lifecycle Methods

Event Handling

Client-Side Events

Form Handling

State Management

Component State

Real-time Updates

Broadcasting Updates

Component Composition

Reusable Components

Performance Optimization

Lazy Loading

Caching

Testing Components

Component Testing

Best Practices

1. Component Design

  • Keep components focused and single-purpose

  • Use composition over inheritance

  • Implement proper lifecycle management

  • Handle cleanup in on_unmount

2. State Management

  • Use immutable state updates

  • Implement proper state serialization

  • Minimize state complexity

  • Use state change listeners

3. Performance

  • Implement lazy loading for large lists

  • Use caching for expensive operations

  • Minimize DOM updates

  • Optimize event handlers

4. Event Handling

  • Validate all event data

  • Use type-safe event structures

  • Implement proper error handling

  • Log important events

Next Steps


Ready to build interactive components? Start with the basic examples above, then explore WebSocket Channels for real-time communication.

Last updated

Was this helpful?