Sub topic 13
Running the dev server and hot updates
This chapter assumes you have already scaffolded a project with npm create vite@latest and run npm install. It also assumes you know basic JavaScript modules and can use a terminal. Here you will start the Vite dev server, see how it serves your code, and learn how hot module replacement (HMR) updates the page without a reload. You will also learn the common problems that break it.
Starting the server
From the project folder, run the dev script defined in package.json:
npm run devVite prints a local URL, by default http://localhost:5173. Open it in a browser and you see the starter app. Keep the terminal open. The server runs until you stop it with Ctrl+C.
Some details about this command:
npm run devruns whatever thedevscript says. In a Vite project that script is simplyvite.- If port 5173 is already in use, Vite picks the next free port (5174, and so on) and prints it. Always read the URL in the terminal rather than assuming the port.
- The server listens on
localhostonly. Other devices on your network cannot reach it unless you pass--host, as innpm run dev -- --host. The extra--tells npm to pass the flag on to Vite. - Vite does not write a bundle to disk in development. The files are served from memory on request.
How the dev server serves your code
Browsers can load JavaScript as ES modules, using import statements in a <script type="module"> tag. Vite relies on this. Your index.html contains a module script that points at /src/main.jsx. The browser requests that file, Vite transforms it, and the browser then requests each file that main.jsx imports.
Vite transforms files only when the browser asks for them. A .jsx file is converted to plain JavaScript on the fly, and imports of packages such as react are rewritten so the browser can resolve them. Packages in node_modules are pre-bundled once, then cached, so the browser does not fetch hundreds of small files for a single library.
This is why start-up is fast. Vite does not need to read and bundle the whole app before it shows you anything. It serves the files that the current page needs.
Hot module replacement
Without HMR, every edit would require a full page reload. A reload throws away everything in the page, including component state. HMR avoids that.
When the page loads, Vite's client code opens a WebSocket connection back to the server. The server watches your files. When you save one, the server works out which module changed and sends a message through the socket. The browser then fetches the new version of that module and swaps it in.
For React, the official plugin (@vitejs/plugin-react) adds a feature called Fast Refresh. It knows how to replace a component's code and re-render it while keeping the state of components that did not change.
Try it yourself
Create a file named src/Counter.jsx from the earlier chapters:
import { useState } from 'react'
function Counter({ label }) {
const [count, setCount] = useState(0)
return (
<button onClick={() => setCount(count + 1)}>
{label}: {count}
</button>
)
}
export default CounterUse it in src/App.jsx:
import Counter from './Counter.jsx'
function App() {
return (
<main>
<h1>My first React app</h1>
<Counter label="Clicks" />
</main>
)
}
export default AppNow run an experiment:
- Click the button until it shows
Clicks: 5. - In
App.jsx, change the heading text and save. The heading changes. The count stays at 5. - In
Counter.jsx, change the button markup, for example to{label} so far: {count}, and save. The text updates and the count is usually still 5. - Change the
useState(0)call touseState(10)and save. Fast Refresh keeps the existing state, so the count may not jump to 10 until you reload the page.
Step 4 surprises many people. The initial value only applies when a component first mounts. State that already exists is preserved on purpose.
Errors and the overlay
Vite shows problems in two places. Syntax errors, such as an unclosed JSX tag, appear in the terminal and as a full-page overlay in the browser. The overlay names the file and line. Fix the error and save, and the overlay disappears without a manual reload.
Runtime errors, such as reading a property of undefined during render, appear in the browser console and in the overlay. A runtime error in one component can unmount the whole React tree. Once you fix it, Fast Refresh usually recovers, but if the page stays blank, reload it.
What Strict Mode does in development
The entry file wraps App in StrictMode. In development only, React uses this to run extra checks. The most visible effect is that components render twice, and effects set up and tear down once more than you expect. If you add console.log inside a component, you will see each message twice. This is intentional, and it does not happen in the production build. It exists to expose code that is not safe to re-run, such as code that changes outside data during render.
Common problems
| Symptom | Likely cause | Fix |
|---|---|---|
| `npm run dev` says `Missing script: "dev"` | You are not in the project folder, or `package.json` has no `dev` script | `cd` into the folder that contains `package.json` |
| `vite: command not found` | Dependencies are not installed | Run `npm install` |
| Page does not open on a different device | Server only listens on `localhost` | Use `npm run dev -- --host` |
| Edits do not appear and the page never updates | WebSocket is blocked, or files are on a network or container volume with no file events | Check the console for WebSocket errors. Configure `server.watch.usePolling` in `vite.config.js` |
| State resets on every edit | The file mixes component exports with other exports, or a component is anonymous | Use named function components and keep one component per file where practical |
| Port differs from the one in your notes | Port 5173 was taken | Read the URL printed in the terminal |
| `Failed to resolve import` | Wrong file path or missing file extension for `.jsx` | Check the path. Vite requires correct case and extensions for your own files |
Stopping and restarting
Stop the server with Ctrl+C. Some changes need a restart because Vite reads them only at start-up. The main example is vite.config.js. Vite usually restarts the server automatically when it detects a change to that file, but if behavior seems stale, stop and start it yourself. Changes to .env files also need a restart before the new values appear.
Exercise
You click a counter to 5, then edit the text in the same component and save. The text changes and the count stays at 5. Then you change useState(0) to useState(10) and save, and the count still shows 5. Why does this happen, and how do you see the new initial value?
Show answer
The initial value passed to useState is used only when the component first mounts. Fast Refresh keeps existing state across edits so you do not lose your place, so the stored value of 5 remains. To see the new initial value, reload the page (or trigger a full remount), so the component mounts again and uses 10.
Exercise
The dev server is running in a container and you edit files on the host through a shared volume. The terminal shows no reaction to your saves, and the browser never updates. Name one likely cause and one configuration change to try.
Show answer
File system events from the shared volume are probably not reaching the container, so the server never notices the change. Enable polling with server: { watch: { usePolling: true } } in vite.config.js, then restart the server. Also check that the browser can open the HMR WebSocket connection, since a blocked WebSocket also stops updates.