Skip to content

Lesson 6 of 9 · 23m

HMR That Survives Reality

Hot module replacement is a state-preservation contract — boundaries, invalidation, and the code shapes that make updates safe.

Hot module replacement feels magical until it corrupts state and developers learn not to trust it. The correct mental model is blunt: HMR executes replacement code inside a live application. Nothing about your old timers, subscriptions, closures, DOM nodes, or module singletons automatically disappears. Framework plugins hide much of this for components, but they cannot make arbitrary side effects safe.

The boundary decides what can be replaced

if (import.meta.hot) {
  import.meta.hot.accept((nextModule) => {
    // decide how the replacement should be applied
  });
}

import.meta.hot.accept() declares “this module can be hot-updated.” If a module is not accepted, invalidation walks upward to an accepting parent; if none exists, the page reloads. That propagation is why an edit to a shared constants file can reload the entire app: everything imports it, so no narrow boundary exists.

State survives only when ownership is clear

let socket;

if (import.meta.hot) socket = import.meta.hot.data.socket;

socket ??= new WebSocket("wss://localhost:4000");

if (import.meta.hot) {
  import.meta.hot.data.socket = socket;
  import.meta.hot.dispose(() => {
    // close it only if the replacement should not inherit it
  });
}

hot.data is a small handoff area across module versions. Use it for deliberately shared runtime handles, not as a junk drawer for application state.

React HMR works because the plugin draws boundaries

React Fast Refresh preserves component state when exports look like components and update shape is compatible. It gives up — correctly — when a file mixes component exports with unrelated mutable runtime exports. That is not pedantry; ambiguous exports make it impossible to know what can safely be re-executed.

Full reload is sometimes the right answer

A reload is better than a subtly wrong live patch. Prefer reloads for:

  • global CSS or design-token changes with broad cascade impact
  • router or store setup modules
  • dependency version changes
  • modules registering global listeners
if (import.meta.hot) {
  import.meta.hot.accept(() => import.meta.hot.invalidate());
}

Invalidation asks the nearest parent to handle it; no parent means reload. Do not fear it — a truthful reload beats counterfeit speed.

Field notes

  • “Stale after edit” often means a module captured the old function in a listener and never removed it.
  • HMR is a dev feature. Never gate production behavior on import.meta.hot.
  • If an edit reloads the whole page unexpectedly, inspect import fan-in to that file.
  • HMR failures in iframes, workers, and multi-window apps are often separate module instances, not one shared runtime.

Was this lesson helpful?

Sign in to rate