Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

Explain the difference between mount(),initializing() and render() method in laravel livewire

Here's the sequence of method calls:

Difference between mount(),initializing() and render() method
when and how mount method called with parameter

__construct: Called when the Livewire component is initialized. This method is typically used to perform initialization tasks or set default property values. It's the first method that is called when the component is created.

initializing: Called before any properties are hydrated. This method is specific to Livewire and is invoked before any property values are set. It's useful for performing tasks before the component's state is initialized.

mount: Called when the Livewire component is first mounted or initialized. This method is typically used to perform tasks when the component is first instantiated. It's called after the __construct method and after the properties have been hydrated.

In summary, the __construct method is called first, followed by the initializing method (if defined), and then the mount method. This sequence allows you to perform initialization tasks at different stages of the component's lifecycle.

How component's properties can be hydrated with initial values using the mount() method

*step1: call route method *

// routes/web.php

use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});
Enter fullscreen mode Exit fullscreen mode

step2: call welcome blade file

<!-- resources/views/welcome.blade.php -->

<!DOCTYPE html>
<html>
<head>
    <!-- Your head content here -->
</head>
<body>
    <livewire:example-component name="Alice" age="30" />

    @livewireScripts
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

step3:Livewire then invokes the render() method of the ExampleComponent class (app/Http/Livewire/ExampleComponent.php)

// app/Http/Livewire/ExampleComponent.php

namespace App\Http\Livewire;

use Livewire\Component;

class ExampleComponent extends Component
{
    public $name;
    public $age;

    public function mount($name, $age)
    {
        $this->name = $name; // Hydrating the 'name' property
        $this->age = $age;   // Hydrating the 'age' property
    }

    public function render()
    {
        return view('livewire.example-component');
    }
}
Enter fullscreen mode Exit fullscreen mode

step 4:Livewire component and you want to render a Blade file named example-component.blade.php

<!-- resources/views/livewire/example-component.blade.php -->

<div>
    <p>Name: {{ $name }}</p>
    <p>Age: {{ $age }}</p>
</div>
Enter fullscreen mode Exit fullscreen mode

Image description

Image description

Top comments (0)