Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Livewire lifecycle hooks
    Livewire lifecycle hooks


Livewire lifecycle hooks


Here are the key points about Livewire's lifecycle hooks:

PHP Lifecycle Hooks

Livewire provides several lifecycle hooks that allow you to execute code at specific points during a component's lifecycle:

- `mount()`: Called when a component is first created and instantiated.
- `hydrate()`: Called when a component is re-hydrated at the beginning of a subsequent request.
- `boot()`: Called at the beginning of every request, both initial and subsequent.
- `updating()`: Called before updating a component property.
- `updated()`: Called after updating a property.
- `rendering()`: Called before the `render()` method is called.
- `rendered()`: Called after the `render()` method is called.
- `dehydrate()`: Called at the end of every component request.
- `exception($e, $stopPropagation)`: Called when an exception is thrown.

You can add these methods to your Livewire component class to hook into the corresponding lifecycle events.

JavaScript Hooks

Livewire also provides JavaScript hooks that allow you to execute custom JavaScript code at specific points in the component's lifecycle:

- `component.initialized`: Called when a component has been initialized on the page by Livewire.
- `element.initialized`: Called when Livewire initializes an individual element.
- `element.updating`: Called before Livewire updates an element during its DOM-diffing cycle after a network roundtrip.
- `element.updated`: Called after Livewire updates an element during its DOM-diffing cycle after a network roundtrip.
- `element.removed`: Called after Livewire removes an element during its DOM-diffing cycle.
- `message.sent`: Called when a Livewire update triggers a message sent to the server via AJAX.
- `message.failed`: Called if the message send fails for some reason.
- `message.received`: Called when a message has finished its roundtrip, but before Livewire updates the DOM.
- `message.processed`: Called after Livewire processes all side effects (including DOM-diffing) from a message.

You can register these hooks in your JavaScript code using the `Livewire.hook()` method.

By leveraging both PHP and JavaScript lifecycle hooks, you can execute custom logic at various stages of a Livewire component's lifecycle, enabling you to perform actions like initializing state, handling updates, and interacting with the DOM.

Citations:
[1] https://livewire.laravel.com/docs/lifecycle-hooks
[2] https://laravel-livewire.com/docs/2.x/lifecycle-hooks
[3] https://laravel-livewire.com/docs/1.x/lifecycle-hooks
[4] https://www.youtube.com/watch?v=QADUTtkH68Q
[5] https://laravel-livewire.com/screencasts/hooks