In Vite 8, how do import.meta.hot.accept, dispose and data let a charting module keep its zoom level across edits?
answer
- the module takes its own update
- clean up before the old copy goes
- one object per module path survives
- mutate it, never replace it
- guard it so production drops it
basics
~10 sThe module self-accepts with import.meta.hot.accept(), its dispose callback writes the zoom into data and destroys the old chart, and the new instance reads import.meta.hot.data.zoom. All of it sits inside if (import.meta.hot).
solid answer
~40 sInside `if (import.meta.hot)`, which is false in production so the block is dropped, the module calls `import.meta.hot.accept()` and becomes its own boundary: an edit re-runs this module instead of reloading the page. Before the new copy runs, Vite calls the `dispose` callback with the module's `data` object; the callback saves `chart.getZoom()` into it and destroys the old chart so canvases and listeners do not pile up. Vite keeps one `data` object per module path, so the new instance reads `import.meta.hot.data.zoom` and restores it. Mutate `data`, never reassign it. Importers are not told about the swap, so this suits a module that mounts itself; a parent can instead accept it with `accept('./route-chart.ts', cb)`, and in Vite 8 that string must resolve as a module id, since the URL fallback was removed.
code
typescript · 16 lines// src/route-chart.ts: mounts itself, exports nothing
import { createChart } from './chart-engine'
const chart = createChart(document.getElementById('route-chart')!)
if (import.meta.hot) {
// restore what the previous copy handed over
chart.setZoom(import.meta.hot.data.zoom ?? 1)
import.meta.hot.dispose((data) => {
data.zoom = chart.getZoom() // mutate data, never reassign it
chart.destroy() // remove the old canvas and listeners
})
import.meta.hot.accept()
}go deeper
Recall that accept makes a module take its own updates, dispose cleans up the old copy, and data carries values to the next copy, all inside an if (import.meta.hot) guard.
Explain the order: dispose receives data before the new copy is imported, the new copy re-runs top-level code and reads data, and importers keep their old bindings.
Choose between self-acceptance and an importer's accept(dep, cb) for modules with exports, use invalidate when a swap is unsafe, and know Vite 8 resolves the dependency string as an id.
Decide where a codebase should invest in hand-written HMR handling for long-lived modules versus accepting reloads, given framework plugins already cover components.
## The client-side HMR API Vite exposes its hot-update API on `import.meta.hot`, which exists only while the dev server serves the module. The members this question needs, and the ones next to them: | Member | What it does | |---|---| | `accept()` / `accept(cb)` | the module accepts its own updates; `cb` receives the new module, or `undefined` after a syntax error | | `accept(dep, cb)` / `accept([deps], cb)` | the module accepts updates of direct dependencies without re-running itself | | `dispose(cb)` | cleanup before the current copy is replaced; `cb` receives `data` | | `prune(cb)` | cleanup only when the module is no longer imported on the page | | `data` | one object per module path, kept across successive copies | | `invalidate(message?)` | give up on this update and pass it to the importers | | `on` / `off` / `send` | listen to `vite:` events, or exchange custom events with the server | A module that accepts is an **HMR boundary**: an edit to it, or to a dependency it accepts, stops there instead of reloading the page. ## Keeping the chart's zoom: the sequence The dispatch console's route chart mounts itself into the page and exports nothing. With the code example's pattern: 1. **First run.** The module creates the chart, and inside the guard sets the zoom from `import.meta.hot.data.zoom`, or `1` when there is none. 2. **You save the file.** Vite sees the module accepts itself and sends an update for it. 3. **Dispose.** Before importing the new copy, the client calls the `dispose` callback with the module's `data`. The callback writes `data.zoom = chart.getZoom()` and calls `chart.destroy()`, so the old canvas, timers and listeners go away. 4. **New copy.** The client imports the edited module with a timestamp query; its top-level code runs again and creates a fresh chart. 5. **Restore.** The new copy reads `import.meta.hot.data.zoom`, which is the same object the old copy wrote, and restores the zoom. Without step 3, each save would typically leave the old chart's canvas and listeners behind and lose the zoom. ## The rules that trip people - **Guard every use.** `if (import.meta.hot) { … }` is false in production, so the whole block is tree-shaken out of the build. - **Write the call literally.** Vite detects acceptance by static analysis and requires the text `import.meta.hot.accept(` exactly; aliasing `import.meta.hot` to a variable and calling `accept` on it is not recognised. - **Mutate `data`, never reassign it.** `import.meta.hot.data.zoom = 2` works; `import.meta.hot.data = { zoom: 2 }` is not supported, and mutating keeps entries other handlers added. - **Pruning clears it.** When a module is pruned, its `dispose` and `prune` callbacks get the current `data`, and Vite clears it afterwards; a later import starts with an empty object. - **Importers are not notified.** Vite re-imports the boundary; modules that imported it keep the bindings they already hold. A self-accepting module that exports functions others call later hands them stale code, which is why the chart mounts itself instead. ## Accepting from the importer instead When the chart module must export a `render(points)` that the console calls, the **parent** can accept it: - `import.meta.hot.accept('./route-chart.ts', (mod) => mod?.render(latestPoints))` re-renders with the new export; the array form takes several dependencies. - **Vite 8 change:** the string is resolved like an import specifier to a module id. Vite 8.0 removed the fallback that accepted a URL there, so a string that cannot be resolved now fails with a resolve error; pass the same specifier the `import` uses. - If the new copy cannot be swapped safely (say its export changed shape), call `import.meta.hot.invalidate()` inside the `accept` callback; Vite then treats the module as not accepting and continues to its importers. ## Where frameworks fit Framework plugins inject `accept` calls into components, so application code rarely writes this API for UI. It earns its place in plain modules with long-lived side effects: a chart, a map engine, a socket client, a polling timer. Each of those owns something outside itself (a canvas, a connection, an interval), and each needs the same three moves: accept so an edit stops at the module, dispose so the old copy releases what it owns, and data so the new copy starts where the old one stopped. For visibility while debugging, `import.meta.hot.on('vite:beforeUpdate', cb)` and `'vite:afterUpdate'` fire around every update the page applies.
- Other modules import render() from the chart module and call it on every feed message; why does self-accepting go wrong there?Vite re-imports the self-accepting module but does not notify its importers, so they keep calling the old `render`, which draws on the chart the dispose callback destroyed. Either keep the module self-contained, or have the importer accept it with `accept('./route-chart.ts', cb)` and switch to the new export in the callback.
- When is prune the right hook instead of dispose?When the module already cleans up its own side effects on each update and only needs to tidy up once it is no longer imported on the page at all. `prune` runs only then; Vite itself uses it for CSS imports. `dispose` runs before every replacement, and also when the module is pruned.
A shift handover: before leaving, the outgoing shift writes the open jobs on the shared whiteboard and clears its desk, and the incoming shift reads that same board first. Wiping the board and hanging a new one loses notes others left.
- Reassigning import.meta.hot.data to a new object is the way to save state
- dispose runs after the updated copy has executed
- Importers automatically receive the new exports of a self-accepting module
- Without an if (import.meta.hot) guard the HMR code is still removed from production
- In Vite 8, accept still takes any URL the dev server serves
Assumes Vite 8; Vite 8.0 removed the fallback that accepted a URL in import.meta.hot.accept, so a dependency is named by a resolvable id.