Livewire v4 components have lifecycle hooks that run at specific times.
Complete Lifecycle Example
class UserProfile extends Component
{
public User $user;
public string $name;
public string $email;
// Runs once when component is first created
public function mount(User $user): void
{
$this->user = $user;
$this->name = $user->name;
$this->email = $user->email;
}
// Runs on every request (before hydration)
public function boot(): void
{
// Good for authorization checks
if (!auth()->user()->can('view', $this->user)) {
abort(403);
}
}
// Runs after component is hydrated from state
public function hydrate(): void
{
// Re-initialize non-persisted data
}
// Runs before a specific property updates
public function updatingName($value): void
{
$this->name = trim($value);
}
// Runs after a specific property updates
public function updatedName($value): void
{
$this->validate(['name' => 'required|min:2']);
}
// Runs before any property updates
public function updating($property, $value): void
{
logger("Updating {$property} to {$value}");
}
// Runs after any property updates
public function updated($property, $value): void
{
logger("{$property} updated to {$value}");
}
public function render(): View
{
return view('livewire.user-profile');
}
}