Creating a project with Vite

React · Essentials · 10 min

Every React project starts with a build setup; Vite is the standard lightweight choice when you aren't using a framework.

React code uses JSX and ES modules, so it needs a build tool. For a client-side app the usual choice is Vite: a fast dev server plus a production bundler. (Create React App is deprecated; if you need routing, data loading and server rendering from day one, the React docs recommend a framework such as Next.js or React Router instead.)

Create and run a project:

npm create vite@latest my-app -- --template react-ts
cd my-app
npm install
npm run dev

Use --template react for plain JavaScript. The dev server (usually on port 5173) supports Fast Refresh: edit a component and it updates in the browser while keeping its state.

The important files:

  • index.html is the real entry point; it contains <div id="root"> and loads src/main.tsx.
  • src/main.tsx creates a React root on that div and renders <App /> inside <StrictMode>.
  • src/App.tsx is your first component. Everything else is components imported from here.
  • vite.config.ts registers @vitejs/plugin-react, which handles JSX and Fast Refresh.

npm run build produces static files in dist/ that any web server can host, and npm run preview serves that build locally. The imports at the top of each file are ordinary ES modules: import { useState } from "react" pulls a named export from the react package.

Example

// src/main.jsx - the entry point Vite generates
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.jsx";
import "./index.css";

createRoot(document.getElementById("root")).render(
  <StrictMode>
    <App />
  </StrictMode>
);

// src/App.jsx
export default function App() {
  return <h1>Hello from React</h1>;
}

Remember

  • npm create vite@latest app -- --template react (or react-ts) scaffolds a project
  • createRoot(el).render(<App />) from react-dom/client mounts React into the page
  • npm run dev for development, npm run build for static production files

Watch out for

  • Starting new projects with Create React App, which is deprecated and unmaintained.

Check yourself

  1. In a Vite React app, what does createRoot(document.getElementById('root')).render(<App />) do?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: react.dev/learn/build-a-react-app-from-scratch