Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon What is the purpose of the hydrate() lifecycle hook
    Livewire lifecycle hooks


What is the purpose of the hydrate() lifecycle hook


The `hydrate()` lifecycle hook in Livewire is used to run code immediately after a component is re-hydrated at the beginning of a subsequent request[1][2][3].

When a Livewire component is first loaded, the `mount()` hook is called to initialize the component. However, on subsequent requests, the `hydrate()` hook is called instead of `mount()`[1].

The `hydrate()` method is useful for:

- Initializing properties that are not persisted between requests[1]
- Performing additional setup or logic that needs to run on every request[2]
- Handling data that is passed to the component via the URL or query string[3]

Here's an example of using the `hydrate()` hook to initialize a property:

php
class ShowPost extends Component
{
    public $postId;
    protected $post;

    public function hydrate()
    {
        $this->post = Post::find($this->postId);
    }
}

In this example, the `$post` property is initialized in the `hydrate()` hook, ensuring it is set up correctly on every request[1].

The `hydrate()` hook is called after the component is instantiated and before any actions are performed or the `render()` method is called[3]. This makes it a convenient place to perform setup tasks and prepare the component for rendering and handling user interactions.

Citations:
[1] https://livewire.laravel.com/docs/lifecycle-hooks
[2] https://laravel-livewire.com/docs/2.x/reference
[3] https://laravel-livewire.com/docs/2.x/lifecycle-hooks
[4] https://laravel-livewire.com/screencasts/hooks
[5] https://laravel-livewire.com/docs/1.x/lifecycle-hooks