DEV Community

Saurabh Mahajan
Saurabh Mahajan

Posted on

3 Tips to improve Livewire Performance

Livewire provides 2 way binding such that any HTML element can be tied to a specific property in Component.

So if you have a Laravel Component like below:

class Product extends Component
{
    public $name;
Enter fullscreen mode Exit fullscreen mode

You can bind this $name variable to any HTML Element using wire:model tag like below:

    <input type="text" wire:model="name" />
Enter fullscreen mode Exit fullscreen mode

So if you change the input field value, $name property of the Component will automatically be updated and vice-versa. If you have used front end Frameworks like Vue or Angular, you are already aware of this concept. However, this binding in Livewire can be expensive. Everytime there is a change in the input value, there will be an AJAX Call fired and whole component will be updated.

In this Article, we will discuss 3 ways to improve Performance:

Using debounce keyword: By default Livewire will send an AJAX Request 150ms after each keystroke. You can increase this time to say 500ms and Livewire will then wait for 500ms before sending an AJAX Request. You can do so by using the following syntax

    <input type="text" wire:model.debounce.500ms="name" />
Enter fullscreen mode Exit fullscreen mode

Using lazy keyword: Sometimes using a debounce is not enough. You can further reduce the AJAX requests by using lazy keyword.

    <input type="text" wire:model.lazy="name" />
Enter fullscreen mode Exit fullscreen mode

Using lazy keyword, Livewire will only send an AJAX Request when you click outside the input field.

Using defer keyword: If there are many fields in your form, using lazy keyword might not be enough. You might only need the values in your component when the form is submitted. For such scenarios you can use the defer keyword like below:

    <form wire:submit.prevent="addProduct">

        <input type="text" wire:model.defer="name"></x-input>
        .
        .
        .

        <button class="mt-4">Submit</button>
    </form>
Enter fullscreen mode Exit fullscreen mode

In the above scenario, no AJAX Call will be fired when you change the input field related to name. However, when you submit the form the corresponding AJAX Request will update the value of $name property.

So depending upon your use case, you can drastically reduce the number of AJAX Requests and improve the performance of your Livewire Components.

For similar articles, you can follow me on Twitter

Top comments (1)

Collapse
 
tanzimibthesam profile image
Tanzim Ibthesam

Did you use Livewire in Production?