Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 38 ยท Dev Server and HMR

Hot Module Replacement

Understand Hot Module Replacement in Webpack: how updates bubble through module.hot.accept, writing accept and dispose handlers, CSS hot updates, framework refresh and common pitfalls.

A full page reload throws away everything the page knew: the text you typed in a form, the scroll position, the open menu, the app state you reached after five clicks. Hot Module Replacement (HMR) swaps only the modules that changed while the page keeps running. Edit a stylesheet and the new CSS appears instantly. Edit a component and just that component updates, with the rest of the state intact.

HMR is on by default in webpack serve (devServer.hot: true, see Webpack Dev Server). Whether a given edit is applied hot depends on whether someone in the module graph accepts the update.

How an update travels

When a file changes, Webpack builds a small "update" containing only the changed modules and tells the browser. The HMR runtime then asks: can this module be replaced? Each module may declare that it handles its own updates (module.hot.accept()). If not, the runtime looks at the module's parents (the modules that import it), and their parents, and so on, up the dependency chain, until it finds one that accepts. If it reaches an entry without finding a handler, HMR gives up and the page reloads fully.

flowchart BT
  C["counter.js (edited)"] -->|"no accept: bubble up"| A["app.js"]
  A -->|"module.hot.accept('./counter.js')"| OK["update applied, app re-runs the callback"]
  A -->|"no accept either"| R["index.js (entry)"]
  R -->|"nobody accepts"| F["full page reload"]

An update bubbles toward the entry until a module accepts it.

module.hot.accept

The raw HMR API is available as module.hot (and import.meta.webpackHot in ES module code). It exists only when HMR is enabled, so guard it.

JavaScript
// app.js
import { render } from './counter.js';

render();

if (module.hot) {
  module.hot.accept('./counter.js', () => {
    // the new counter.js is already evaluated here
    render();
  });
}

Accepting a dependency means "when counter.js changes, call my callback instead of reloading". Inside you re-run whatever uses the new version. Accepting your own updates is also possible with module.hot.accept() and no arguments, which is common for leaf modules with no side effects.

Node.js Stand-in: bubbling updates to an accepting module

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Dispose: clean up and keep state

When a module is replaced, its old version may have created timers, listeners or DOM nodes. If you do not remove them, you get duplicates after each edit. module.hot.dispose runs just before the old module goes away, and its data object is passed to the next version, so you can carry over state.

JavaScript
// clock.js
const previous = module.hot?.data;                // data from the old version
let seconds = previous?.seconds ?? 0;

const timer = setInterval(() => { seconds += 1; render(seconds); }, 1000);

if (module.hot) {
  module.hot.dispose((data) => {
    clearInterval(timer);                         // stop the old timer
    data.seconds = seconds;                       // hand state to the new module
  });
  module.hot.accept();
}
Node.js Stand-in: dispose cleans up, data carries state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

CSS and framework integration

  • CSS updates hot out of the box when style-loader is used, because it contains accept logic that replaces the <style> tag (CSS and Style Loaders). Extracted CSS (MiniCssExtractPlugin) can also hot-reload in development with its HMR support, but many projects keep style-loader in dev.
  • React: @pmmmwh/react-refresh-webpack-plugin plus react-refresh/babel keeps component state across edits. You rarely write module.hot yourself.
  • Vue: vue-loader includes HMR for single-file components.
  • Angular, Svelte and others: provided by their loaders or tools.

For frameworks you usually do nothing by hand, because their loaders insert the accept calls. Writing module.hot.accept yourself matters for vanilla apps, stores, and your own tooling.

Enabling and disabling HMR

JavaScript
devServer: { hot: true },          // HMR, with full reload as a fallback
// devServer: { hot: 'only' },     // HMR only: no fallback reload (errors stay visible)
// devServer: { hot: false, liveReload: true }, // just refresh the page

You rarely add HotModuleReplacementPlugin yourself: devServer.hot does it. If an update fails, check the console for [HMR] messages; they explain which modules were updated and why a fallback happened.

Pitfalls

  • Side effects at module level (registering listeners, adding DOM nodes) repeat on each update unless disposed.
  • Singletons and module state are reset when a module is replaced. Keep state in a store module that accepts updates and carries over data.
  • HMR never runs in production builds. module.hot is undefined, and bundlers remove the guarded code in production.
  • Guard calls: always if (module.hot) so the code still runs when HMR is off.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens when an edited module and all its parents do not accept the update?

    An update that no module accepts cannot be applied hot, so the fallback is a full reload.
  2. 2. What does module.hot.accept('./counter.js', cb) declare?

    It registers the importing module as the handler for updates of the dependency.
  3. 3. Why use module.hot.dispose?

    Dispose runs before replacement, so timers and listeners are removed and state can be handed over.
  4. 4. Why do React projects need a refresh plugin instead of hand-written accept calls?

    React Refresh tooling wires up accept boundaries automatically for components.

Summary

  • HMR replaces changed modules at runtime, keeping the page state; it is on by default in the dev server.
  • Updates bubble from the changed module to its parents until one calls module.hot.accept; otherwise a full reload happens.
  • Use dispose to remove timers and listeners and pass state through data.
  • Style loaders and framework plugins (React Refresh, vue-loader) provide the accept logic for you.
  • Always guard module.hot and never rely on it in production.

Next: Source Maps