How to Refresh or Re-Render a Livewire Component (4 Techniques)

June 27th, 2024 • Last updated 2 minutes read time

Need to manually re-render a Livewire component to update its contents? Let's discuss a few easy ways to do this.

All of these techniques work with Livewire 3, and should also work with Livewire 2 if you're still on that version.

At the heart of everything is the built-in $refresh action which refreshes an entire Livewire component, and is probably all you'll need if you're just looking to refresh everything in a Livewire page or component.

Here's the entire implementation:

class SomeComponent extends Component
{
    protected $listeners = [
        'some-event' => '$refresh'
    ];

    public function someAction()
    {
        $this->dispatch('some-event');
    }
}

In this component, if a some-event event is dispatched, the $refresh action will be invoked, which will refresh your Livewire component.

Since we can globally dispatch events, you can refresh any component in response to an action in another component. I covered this in the Livewire Trello Clone course here on Codecourse.

If you need to refresh the component from within itself and don't need to rely on events, there's a much easier way. In the template for your Livewire component, just invoke $refresh directly.

<button wire:click="$refresh">Refresh this component</button>

The click event above triggers a call to the $refresh action and will re-render the Livewire component. Exactly the same as the previous technique we looked at, just directly calling $refresh instead.

Oh, we can do it from Alpine too! Using Alpine to refresh a Livewire component is helpful when you need to refresh your component inside a JavaScript condition or event.

Here's an example of refreshing a Livewire component every 5 seconds (not recommended for most scenarios, but could be useful).

<div
    x-init="
        setInterval(() => {
            $wire.$refresh()
        }, 5000)
    "
>
    This will get refreshed every 5 seconds
</div>

Of course, you can also directly link this to a button action using Alpine.

<button x-on:click="$wire.$refresh()">
    Refresh this component using an Alpine click event!
</button>

The $commit helper does the same thing as $refresh (they're entirely identical). So, if you prefer this, you can also invoke this to re-render a Livewire component.

<button wire:click="$commit">
    Refresh this component using $commit!
</button>

That's a wrap — you're spoiled for choice when it comes to methods for re-rendering Livewire components.

If you found this article helpful, you'll probably love our practical screencasts!
Author
Alex Garrett-Smith

Comments

No comments, yet. Be the first!