Back to Course |
Livewire 3 From Scratch: Practical Course

Lazy Loading Components

Sometimes you have a component where it will have a lot of data to fetch from the DB and then do some calculations before showing stats or charts. Or you have a big blog with millions of comments, and it takes some time to load a post because of those comments. Let's see how we can load some components after loading the whole page.


In the earlier lesson, we added comments. Let's add a new ShowComments Livewire component.

use App\Models\Post;
use Livewire\Component;
use Illuminate\Support\Collection;
use Illuminate\Contracts\View\View;
 
class ShowComments extends Component
{
public Collection $comments;
 
public function mount(Post $post): void
{
$this->comments = $post->comments()->get();
}
 
public function render(): View
{
return view('livewire.show-comments');
}
}
<div class="space-y-1">
@foreach($comments as $comment)
<p>{{ $comment->body }}</p>
@endforeach
</div>

It's just a simple component where we get comments for the post and show the body of the comment.

Typically we would call this component like so:

<livewire:show-comments :post="$post" />

But now we can add the lazy attribute:

<livewire:show-comments :post="$post" lazy />

After this, Livewire will skip this component until the whole page gets loaded, and only then will it make the query and render it.

Of course, just showing nothing while the page is loading isn't good. Livewire lets you add a placeholder which can be just a basic text saying Loading or an SVG icon. This can be done by adding a placeholder method to the Livewire component.

class ShowComments extends Component
{
// ...
 
public function placeholder(): string
{
return <<<'HTML'
<div>
Loading...
</div>
HTML;
}
 
// ...
}