Vite with React
Vite is the most common way to start a new client-side React app. The official template gives you JSX, TypeScript, Fast Refresh (HMR that keeps component state) and an optimized production build in seconds.
Create the project
npm create vite@latest react-shop -- --template react-ts
cd react-shop
npm install
npm run dev> npx
> create-vite react-shop --template react-ts
│
◇ Scaffolding project in /home/me/react-shop...
│
└ Done.
added 186 packages, and audited 187 packages in 12s
found 0 vulnerabilities
> react-shop@0.0.0 dev
> vite
VITE v8.3.4 ready in 402 ms
➜ Local: http://localhost:5173/
➜ Network: use --host to expose
➜ press h + enter to show help
react-shop/
├── index.html
├── vite.config.ts
├── eslint.config.js
├── tsconfig.json, tsconfig.app.json, tsconfig.node.json
├── public/vite.svg
└── src/
├── main.tsx ← createRoot(...).render(<App />)
├── App.tsx
├── App.css
├── index.css
└── assets/react.svgThe config
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
});| Plugin | Notes |
|---|---|
@vitejs/plugin-react |
Default. JSX handled by Vite's built-in transform; adds React Fast Refresh. Optional Babel plugins (e.g. the React Compiler) via react({ babel: { plugins: [...] } }) |
@vitejs/plugin-react-swc |
Uses SWC for JSX and Fast Refresh; supports SWC plugins. Pick with the react-swc-ts template |
Entry point
// src/main.tsx
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import './index.css';
import App from './App.tsx';
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
);// src/App.tsx
import { useState } from 'react';
import reactLogo from './assets/react.svg';
export default function App() {
const [count, setCount] = useState(0);
return (
<main>
<img src={reactLogo} alt="React logo" />
<button onClick={() => setCount((c) => c + 1)}>count is {count}</button>
</main>
);
}Note the asset import (reactLogo) works exactly as you learned earlier — it's a URL.
What JSX compiles to
Browsers don't understand JSX. Vite compiles <button onClick={f}>Hi</button> into function calls from react/jsx-runtime. The playground uses a homemade jsx function with the same shape to show the idea — JSX is just a nicer way to write nested calls that return objects:
// What the compiler emits for:
// <ul className="list">{items.map(i => <li key={i}>{i}</li>)}</ul>
const jsx = (type, props) => ({ type, props });
const items = ['Vite', 'React'];
const tree = jsx('ul', {
className: 'list',
children: items.map((i) => jsx('li', { key: i, children: i })),
});
function toHtml(node) {
if (typeof node === 'string') return node;
const { children = [], className } = node.props;
const kids = (Array.isArray(children) ? children : [children]).map(toHtml).join('');
const cls = className ? ` class="${className}"` : '';
return `<${node.type}${cls}>${kids}</${node.type}>`;
}
console.log(JSON.stringify(tree.props.children[0]));
console.log(toHtml(tree));{"type":"li","props":{"key":"Vite","children":"Vite"}}
<ul class="list"><li>Vite</li><li>React</li></ul>
Fast Refresh
With the React plugin, editing a component re-renders it without losing state — change the button text while count is 7, and it stays 7. Rules to keep it working:
- A file should export only components (a
.tsxfile that also exports a constant or helper function causes a full reload). The ESLint rulereact-refresh/only-export-componentsin the template warns about this. - Components should be named functions or
constarrow functions with capitalized names. - Editing a non-component module (like a
utils.ts) re-runs the components that import it.
Calling an API in dev
Combine React with the proxy from the previous lesson:
import { useEffect, useState } from 'react';
type Course = { id: string; title: string };
export function CourseList() {
const [courses, setCourses] = useState<Course[]>([]);
useEffect(() => {
fetch('/api/courses')
.then((r) => r.json())
.then(setCourses);
}, []);
return <ul>{courses.map((c) => <li key={c.id}>{c.title}</li>)}</ul>;
}The result, without React
Under the hood, all of this ends up as normal DOM. Here's the counter from the template rebuilt with plain JavaScript, just to see the behaviour:
<!doctype html>
<html>
<body style="font-family: system-ui; text-align: center; padding: 1.5rem">
<div id="root"></div>
<script type="module">
let count = 0;
const root = document.getElementById('root');
function App() {
root.innerHTML = `
<h1>Vite + React</h1>
<button id="btn" style="padding:.6rem 1.2rem;border-radius:8px;border:1px solid #646cff">count is ${count}</button>
<p>Edit <code>src/App.tsx</code> and save to test HMR</p>`;
root.querySelector('#btn').onclick = () => { count++; App(); };
}
App();
</script>
</body>
</html>Building
npm run build> react-shop@0.0.0 build
> tsc -b && vite build
vite v8.3.4 building client environment for production...
✓ 32 modules transformed.
dist/index.html 0.46 kB │ gzip: 0.29 kB
dist/assets/react-CHdo91hT.svg 4.13 kB │ gzip: 2.05 kB
dist/assets/index-D8b4DHJx.css 1.39 kB │ gzip: 0.71 kB
dist/assets/index-Bq2j5dXk.js 194.05 kB │ gzip: 61.02 kB
✓ built in 412ms
Tip: Need routing, data loading and SSR? Frameworks like React Router (framework mode) and TanStack Start are themselves built on Vite, so everything in this course still applies.
Test yourself
Which plugin enables JSX and Fast Refresh in a Vite React app?
- @vitejs/plugin-vue
- @vitejs/plugin-react
- vite-plugin-jsx
- No plugin is needed
What keeps a React component's state when you edit and save it?
- Full page reload
- React Fast Refresh
- Service workers
- localStorage
A .tsx file exports a component and a constant. What may happen on edit?
- Nothing changes
- Fast Refresh may fall back to a full reload
- The build fails
- The constant is deleted