Guide
Configure Vite Hot Module Replacement to Preserve UI State
Learn how to use Vite's HMR API to update modules while keeping UI state intact, with example code, verification steps, and recovery tips.
Published by Tasadduq Burney
17 Mar 2026, 14:18 UTC
2 min132K views0

Desired outcome
When you edit a source file during development, Vite's Hot Module Replacement (HMR) updates only the changed module in the browser while keeping the existing application state (e.g., form values, scroll position) intact.
Prerequisites
- A project initialized with Vite (e.g.,
npm create vite@latest my-app -- --template vanillaor any framework template). - Node.js ≥14 and a package manager (npm, yarn, or pnpm).
- The Vite development server running (
vite devorvite).
Procedure
- Open the module you want to make HMR‑aware. This could be a JavaScript file, a Vue SFC, or a React component.
- Add a check for the HMR API provided by Vite:
if (import.meta.hot) {
import.meta.hot.accept((newModule) => {
// Optional: run logic when the module is accepted.
// newModule is the updated module object.
});
}
- If the module holds state that must be cleaned up before replacement, provide a dispose handler:
if (import.meta.hot) {
import.meta.hot.dispose((data) => {
// Clean up timers, event listeners, or subscriptions.
// Example: clearInterval(timerId);
});
import.meta.hot.accept((newModule) => {
// Re‑initialize state using the new module if needed.
});
}
- Save the file. The Vite dev server will push a message over the WebSocket connection, the browser will invalidate the module, and the accept callback will run.
Expected checks
- Open the browser console; after saving you should see a log similar to
[vite] hot updated: /src/example.js. - Verify that UI state you expect to persist (e.g., text in an
<input>) remains unchanged after the update. - In the DevTools Network tab, filter by JS and confirm that only the modified file (and its imports) is requested; no full bundle reload occurs.
Recovery options
- If the console shows an error and the page reloads, check that the module does not contain syntax errors and that any disposed resources are properly cleared.
- To temporarily disable HMR, add
server: { hmr: false }tovite.config.jsand restart the dev server. - If a dependency lacks ESM support, install
@vitejs/plugin-legacyor configureoptimizeDepsto include it.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.