Vite

How Vite HMR updates modules and preserves state

Trace Vite hot module replacement through its module graph and WebSocket, then use hot.accept, hot.dispose, hot.data, and custom events.

How Vite HMR updates modules and preserves state

Vite’s development server can replace a module while the page stays open. I use its manual HMR API when a module needs to keep state, stop a timer, or exchange development events outside the framework’s normal update handling.

From a file change to an update boundary

The dev server tracks module relationships. When a file changes, Vite invalidates affected modules and follows their importers until it finds a boundary that accepts the update. It can reload the page if the change cannot be handled through an accepted boundary. The browser receives the update over the development WebSocket and fetches updated modules through its ESM loader.

flowchart TD
    EDIT["Edit a source file"] --> GRAPH["Invalidate affected modules"]
    GRAPH --> BOUNDARY{"Accepting boundary?"}
    BOUNDARY -->|"Yes"| SOCKET["Send update over WebSocket"]
    SOCKET --> CLIENT["Reload affected ESM modules"]
    BOUNDARY -->|"No"| RELOAD["Reload page"]
1
2
3
4
5
6
7
8
9
10
11
12
// Example HMR payload sent to the browser over WebSocket.
{
  type: 'update',
  updates: [
    {
      type: 'js-update',
      path: '/src/features/counter.ts',
      acceptedPath: '/src/features/counter.ts',
      timestamp: 1787625600123
    }
  ]
}

The update is scoped to the module graph, so a replacement does not automatically reset every stateful object in the page. Framework integrations supply their own boundaries. I reach for the raw API when I manage a module’s lifecycle directly.

Accepting an update and releasing resources

A self-accepting module uses hot.accept() to tell Vite it can handle replacement. Use hot.accept(dependency, callback) when the parent has kept control of the dependency and can swap its exported value safely. Keep the recognizable if (import.meta.hot) guard so the development branch can be removed in production builds.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// src/features/counter.ts
export let count = 0;

export function increment(): void {
  count += 1;
  console.log(`[Counter] Current count: ${count}`);
}

// Accept updates to this module.
if (import.meta.hot) {
  import.meta.hot.accept((newModule) => {
    if (newModule) {
      console.log('[HMR] Counter module updated successfully.');
    }
  });
}

A timer started at module scope will survive replacement unless the module cancels it. Use hot.dispose() for timers, subscriptions, sockets, and custom HMR listeners installed by the old version.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// src/services/heartbeatService.ts
class HeartbeatService {
  private timerId: number | null = null;

  public start(): void {
    if (this.timerId !== null) return;
    this.timerId = window.setInterval(() => {
      console.log(`[Heartbeat] Ping at ${new Date().toISOString()}`);
    }, 3000);
  }

  public stop(): void {
    if (this.timerId !== null) {
      clearInterval(this.timerId);
      this.timerId = null;
      console.log('[Heartbeat] Timer cleared.');
    }
  }
}

export const heartbeat = new HeartbeatService();
heartbeat.start();

// Clean up the outgoing module.
if (import.meta.hot) {
  import.meta.hot.dispose(() => {
    heartbeat.stop();
  });
}

Keeping useful state between module instances

hot.data belongs to a module’s HMR lifetime. Store the minimum state that the next instance can understand, using properties of the existing data object. A new instance can use those values rather than resetting them. Replace or validate stale values when a state shape changes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// src/stores/persistedSession.ts
interface SessionState {
  userId: string;
  loginTime: number;
}

// Restore the saved HMR state or initialize it.
export const sessionState: SessionState = (import.meta.hot && import.meta.hot.data.cachedSession) 
  ? import.meta.hot.data.cachedSession 
  : {
      userId: 'usr_guest',
      loginTime: Date.now()
    };

export function updateUserId(newId: string): void {
  sessionState.userId = newId;
}

if (import.meta.hot) {
  // Save state before replacing the module.
  import.meta.hot.dispose((data) => {
    data.cachedSession = sessionState;
  });

  import.meta.hot.accept();
}

State does not need to be sent across the WebSocket to survive replacement. Simple values are still a useful choice because code running after an edit must be able to interpret them. Long-lived objects with active resources need an explicit handoff or cleanup policy.

Sending custom development events

A Vite plugin can register a server-side event listener and send a reply to one client or publish a development update to all connected clients. The client uses hot.send() and hot.on(). The example sends a small metric payload and returns an acknowledgment.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// plugins/hmrMetricBridgePlugin.ts
import type { Plugin, ViteDevServer } from 'vite';

export function hmrMetricBridgePlugin(): Plugin {
  return {
    name: 'vite-plugin-hmr-metric-bridge',
    configureServer(server: ViteDevServer) {
      // Receive a custom event from the client.
      server.ws.on('app:client-metric', (data, client) => {
        console.log(`[vite:custom-ws] Received metric from client:`, data);

        // Acknowledge the event to the initiating client.
        client.send('app:server-ack', {
          status: 'SUCCESS',
          receivedAt: Date.now()
        });
      });

      // Broadcast a server-side development event.
      server.ws.send('app:config-sync', {
        theme: 'dark',
        featureFlags: { betaTable: true }
      });
    }
  };
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// src/telemetry/hmrClientTelemetry.ts
if (import.meta.hot) {
  // 1. Send the client's runtime metrics.
  import.meta.hot.send('app:client-metric', {
    fps: 60,
    memoryMb: 42.1,
    route: window.location.pathname,
    timestamp: Date.now()
  });

  // 2. Receive the server acknowledgment.
  import.meta.hot.on('app:server-ack', (payload) => {
    console.log('[HMR Client] Server acknowledged payload:', payload);
  });

  // 3. Receive a server configuration broadcast.
  import.meta.hot.on('app:config-sync', (config) => {
    console.log('[HMR Client] Syncing runtime config:', config);
  });
}

These messages are development tooling. They are separate from the application’s production delivery channels. When a module registers a callback repeatedly, retain its function reference and remove it with hot.off() during disposal.

Checking a replacement and its side effects

Modify the counter while the page is open and inspect the terminal and browser. A module update should arrive without reloading the page when the boundary accepts it.

Vite update logs and the client WebSocket activity Figure 1. The development server emits an HMR update after a file edit.

Client and server logs for a custom HMR request and acknowledgment Figure 2. The custom development event travels to the server and back.

Repeat the edit several times. Verify that one timer and one event callback run per update, that carried state is still valid, and that the production build does not contain the debug behavior. Vite HMR API

This post is licensed under CC BY 4.0 by the author.