matt murtaugh.
about. skills. work. uses. blog.

Snappier components with Livewire & AlpineJS

I regularly find myself trying to determine what is the proper way to build Livewire components. The beautiful thing about Livewire is that it’s extremely flexible, but with flexibility comes issues.

Recently I was working on refactoring an older Livewire project, and I noticed a negative pattern scattered throughout the whole project. What’s worse is that I still do this in my current work.

So, what’s wrong with the project?

Animations within my components are slow. Under the hood, I’m using AlpineJS for almost every piece of JS. I know that Alpine isn’t slow, so why does everything have a delay?

The simple answer is that I’m letting Livewire handle variables instead of AlpineJS.

Say you have a component that looks like this:

<div x-data="{ showFilters: @entangle('showFilters') }">
    <button wire:click="$toggle('showFilters')">Show filters</button>

    <div x-show="showFilters" x-collapse>
        // Some filters here

I wouldn’t normally entangle showFilters, but I want Livewire to be aware of this variable. I show filters on page load if there are any query parameters. The variable isn’t always set, but I want the component to show the filters automatically if any exist.

Do you see my problem here? If not, that’s okay. I didn’t either.

The problem with this code is that even though I’m entangling the showFilters Alpine variable, I’m relying on Livewire to update it. Using $toggle('showFilters') I’m asking the component to have a round trip to the server before updating my showFilters variable.

Only changing JS function within the button wire:click="$toggle('showFilters')" to x-on:click="showFilters = !showFilters" has a drastic effect on the snappiness of the component. The filters will update instantly when clicking the button. I don’t lose any functionality with this change. Livewire still knows the value of showFilters, but it doesn’t know it until after the visual change is made on the page.

© 2024 matt murtaugh. All rights reserved.