Components
A component is a Rust struct whose fields are the state on the wire, plus an impl block that publishes its actions.
use livewire::{LivewireComponent, component};
use livewire::component::ComponentContext;
#[derive(Default, LivewireComponent)]
#[livewire(view = "livewire.counter")]
pub struct Counter {
pub count: i32,
pub step: i32,
#[livewire(validate(required, max_length(10)))]
pub label: String,
#[livewire(url(as = "q", use = "replace"))]
pub search: String,
#[livewire(session(key = "counter-selection"))]
pub selection: i64,
#[livewire(locked)]
pub id: String,
#[livewire(skip)]
pub renders: u32,
}
#[component(isolate, transition = "fade")]
impl Counter {
pub fn mount(&mut self, count: Option<i32>) {
self.count = count.unwrap_or(0);
self.step = 1;
self.id = laravel::str::random(20);
}
pub fn increment(&mut self) {
self.count += self.step.max(1);
}
#[livewire(on = "counter-reset")]
pub fn reset_from_event(&mut self) {
self.count = 0;
}
#[livewire(computed)]
pub fn doubled(&self) -> i32 {
self.count * 2
}
#[livewire(json)]
pub fn report(&mut self) -> serde_json::Value {
serde_json::json!({"count": self.count})
}
#[livewire(renderless)]
pub fn quietly(&mut self) {}
#[livewire(authorize(deny))]
pub fn secret(&mut self) -> &'static str {
"the answer is 42"
}
}This is the component the section below explains, rendered by the deployed lab rather than by a screenshot.
The derive writes the field table. The attribute macro writes the lifecycle forwarding and the action dispatch. Nothing is reflected over at runtime, and the server never builds a type whose name came from the browser.
A component in full
This is the demo counter: a typed field, a locked field, a query-string field, a session-backed field, a listener, and four method options.
use livewire::{LivewireComponent, component};
use livewire::component::ComponentContext;
#[derive(Default, LivewireComponent)]
#[livewire(view = "livewire.counter")]
pub struct Counter {
pub count: i32,
pub step: i32,
#[livewire(validate(required, max_length(10)))]
pub label: String,
#[livewire(url(as = "q", use = "replace"))]
pub search: String,
#[livewire(session(key = "counter-selection"))]
pub selection: i64,
#[livewire(locked)]
pub id: String,
#[livewire(skip)]
pub renders: u32,
}
#[component(isolate, transition = "fade")]
impl Counter {
pub fn mount(&mut self, count: Option<i32>) {
self.count = count.unwrap_or(0);
self.step = 1;
self.id = laravel::str::random(20);
}
pub fn increment(&mut self) {
self.count += self.step.max(1);
}
#[livewire(on = "counter-reset")]
pub fn reset_from_event(&mut self) {
self.count = 0;
}
#[livewire(computed)]
pub fn doubled(&self) -> i32 {
self.count * 2
}
#[livewire(json)]
pub fn report(&mut self) -> serde_json::Value {
serde_json::json!({"count": self.count})
}
#[livewire(renderless)]
pub fn quietly(&mut self) {}
#[livewire(authorize(deny))]
pub fn secret(&mut self) -> &'static str {
"the answer is 42"
}
}
The struct
The type must implement Default, must use named fields, and must not be generic: a later request rebuilds it from a snapshot and then reads the fields the snapshot holds.
One attribute selects the template. #[livewire(view = "livewire.counter")] names a .livewire file through the view finder. #[livewire(inline = "<div>...</div>")] stores the source in the struct. With neither, the view is livewire.{kebab-case type name}, so PostEditor renders livewire.post-editor. Declaring both is a compile error.
#[derive(Default, LivewireComponent)]
#[livewire(inline = "<p>count: {{ count }}</p>")]
pub struct Badge {
pub count: i32,
}
Field forms
Fields cross the wire in declaration order. Every attribute is optional; a field with none is plain JSON state.
| Attribute | Crosses the wire | What it does |
|---|---|---|
skip | no | Never serialized and never accepted from the browser. The field keeps its default from one render to the next in one request. |
locked | yes | The browser may read it, never change it: an update or a $set answers 419. mount does not read a locked field from a prop either. |
modelable | yes | Recorded in the field table as bindable. Parent-to-child binding (memo.bindings) is not implemented, so nothing reads the flag yet. |
reactive | yes | A value the parent passed in this request replaces the field before the child renders, and an unchanged child answers {"skip":true}. |
synth(path::to::Synth) | yes | The field's value goes through that synthesizer, whose KEY the snapshot records. The field declares the adapter's own type. |
model | yes | Shorthand for the model reference: declare ModelRef<Post>, the snapshot keeps a key, and the row is fetched before the hooks and the render. |
form | yes | A struct of wire-public fields crosses as one plain JSON object. Dotted updates are consolidated into the object path. |
url(..) | yes | Reads its first value from the page's query string and describes itself to the client in effects.url. |
session(..) | no | Renders on the page, persists in the session, and is removed from data before the snapshot is signed. |
validate(..) | yes | Rules the component runs against itself. See Actions & validation. |
Query-string fields
url takes as, use, always_show, and except. use accepts only "push" or "replace"; anything else is a compile error.
#[livewire(url(as = "page", use = "push", always_show = true, except = "keep"))]
pub page: i64,
The mount writes this effect, which the client keeps for the life of the component:
"url": {
"page": { "as": "page", "use": "push", "alwaysShow": true, "except": "keep" }
}
An update has no query string of its own, so the first value is read from the Referer query, which is what upstream reads.
Session-backed fields
A field with session is written to the session when the component dehydrates and read back when it hydrates, with the snapshot value taking precedence. session(key = "counter-selection") names the key; without it the key is lw{crc32} of the component and field names, so two components with a field of the same name do not share a value. A {path} in a configured key is filled from the component's current state.
The impl block
Only an inherent method that appears in the annotated implementation is reachable from the browser, and only when it is public and is not a lifecycle method. Class options go on the attribute, method options on the method.
| Class option | Effect |
|---|---|
lazy, defer | The first render is a placeholder with wire:init="__lazyLoad"; the update that follows renders the view and sets memo.lazyLoaded. |
isolate | The snapshot records memo.isolate, so the client sends this component's requests alone. |
transition = "fade" | Every render adds effects.transition = {"type": "fade"}. |
layout = "layouts.app", title = "Posts" | Accepted and recorded, but not read yet: a page component names its layout in its own view with {% extends "layouts.app" %}. |
| Method option | Effect |
|---|---|
on = "event" | The method listens for that event. The name reaches the browser in effects.listeners. |
renderless | The response carries effects.skipRender = true, so no new markup is sent. |
json | The return value is the response body. The method is listed in memo.json and memo.async. |
async | The client sends this call ahead of the others; the method is listed in memo.async. |
authorize(path::to::policy) | A refused call is 403. The policy is async fn(&mut Self) -> Result<bool, String>. |
computed | The method's value is available to the template like a field, memoized for the request. It is not dispatchable. computed(..) with options is refused at compile time. |
A method named authorize in the impl is refused: the macro generates the trait's method from the actions' policy paths. A private method is ignored rather than published.
Lifecycle
Every method has a default, so a component implements only what it needs. The order is upstream's, and the browser depends on it.
First render. boot, initialize, mount, booted, render, dehydrate, destroy. The BeforeMount hook runs first and the Mount hook last, once the wire attributes are injected.
Update. The snapshot's fields hydrate, then boot, initialize, hydrate. Model references resolve. A reactive field takes the parent's value. BeforeUpdate runs, then each update: updating, the assignment, and after all assignments one updated per distinct root field. The calls run in the order the browser sent them, then model references resolve again, the Update hook runs, returns is written, and the component renders unless an action or a redirect said not to. Finally dehydrate and destroy.
render returns a ComponentView. Its markup must have exactly one root element: none answers RootTagMissing, several answer MultipleRootElements, both 500.
Watching every component
A hook is registered once on the registry and sees each step for each component.
use livewire::hooks::HookEvent;
components.hook(|event| {
if let HookEvent::Call { name, id, method } = event {
println!("{name} {id} ran {method}");
}
});
| Event | When |
|---|---|
BeforeMount { name } | Before mount, with no instance ID yet. |
Mount { name, id } | After the first render and the attribute injection. |
BeforeUpdate { name, id } | Before the fields change. |
Update { name, id } | After the calls, before the response is written. |
BeforeCall { name, id, method } | Before one action runs. |
Call { name, id, method } | After it ran, whether it succeeded or failed. |
The view
A component view is a MiniJinja template with the .livewire extension, at resources/views/livewire/{name}.livewire. The component's fields are its data; {{ name }} prints a field, and {% if %} and {% for %} are ordinary Jinja. The framework's helpers are present: url, route, csrf_token, csrf_field, session, vite, attributes, and the date, for_humans, and js filters.
<div class="card" wire:key="counter-{{ id }}">
<h2>{{ label }}</h2>
<p>Count: <strong>{{ count }}</strong> doubled: {{ doubled }}</p>
<label>Step
<input type="number" wire:model.live="step">
</label>
<button type="button" wire:click="increment">+</button>
<button type="button" wire:click="reset">Reset</button>
</div>
Inside a component view, {{ livewire("child", {"post": 3}, "row-3") }} mounts a child, and <livewire:child> does the same. The nesting rules are on Composition.
Registration
The application registers components once, in its provider. The name is what the template and the snapshot use.
use livewire::{ComponentRegistry, LivewireServiceProvider};
providers.add(LivewireServiceProvider::new(
|components: &mut ComponentRegistry| {
components
.register::<Counter>("counter")
.expect("the counter is registered once");
components
.register::<PostBrowser>("post-browser")
.expect("the page component is registered once");
components.hook(|event| { /* see above */ });
},
));
register::<C>(name) builds each instance with C::default(); register_with::<C>(name, factory) uses a closure instead. A duplicate name or a name with characters outside letters, digits, dashes, dots, slashes and :: stops the provider. register_synth::<S>() adds a synthesizer key, and templates(|environment| ...) extends the .livewire environment.
The registry is shared through the container and frozen before the application boots, so two applications in one test process keep their own components. There is no global component table.
What this port leaves out
There is no attribute for trait-based form objects or a policy object registered once: a form object is a struct annotated with the derive and marked #[livewire(form)], and a policy is a per-action function. PHP-style container injection into actions is absent: an action that needs a service takes it from the request it is given.