Back to articles

Prevent Livewire Refreshes and State Loss When Hot Reloading with Vite

February 22nd, 2024

If you're here, you're likely suffering from unexpected state loss in your Livewire components when using Vite.

Here's the picture — you fire up npm run dev and start building your Livewire components. But, as soon as you change something and head back to your browser to interact with your Livewire components, your browser seems to refresh itself, and/or you lose all current state in your Livewire components.

Pretty annoying.

There's an easy solution

The vite-livewire-plugin solves this issue by configuring Vite for use with Livewire. Here's how to add it.

First up, install the plugin with npm.

npm install --save-dev @defstudio/vite-livewire-plugin

Next, add the plugin to your vite.config.js file and point it to your CSS files so they can get refreshed too.

import livewire from '@defstudio/vite-livewire-plugin'

export default defineConfig({
    // ...
    plugins: [
            input: [
            refresh: false,

            refresh: ['resources/css/app.css'],

You'll also want to explicity set refresh to false with the Laravel Vite plugin to avoid conflicts (see above).

Finally, add the hot reload manager to your app.js file.

import { livewire_hot_reload } from 'virtual:livewire-hot-reload'


That's it!

You should no longer have any issues with unexpected refreshing or state loss when working with Livewire and Vite.

I'd highly recommend heading to the GitHub repository for vite-livewire-plugin to see more options, and keep up to date with any changes to the plugin.

A massive thanks to Fabio Ivona from def:studio for authoring this plugin and saving us all from unexpected state changes when using Livewire under Vite!

Alex Garrett-Smith


No coments, yet. Be the first to leave a comment.