React with Vite - Setup and First Steps

Introduction

Vite is a modern build tool that allows us to develop ultra fast. It's one of the tools for running React and one of the most used today.


Why Vite with React?

The problems of the past

Before, we had Create React App (CRA) which was the official tool. But it was slow, heavy, and not optimized for modern development.

The advantages of Vite

  • Ultra-fast Hot Module Replacement (HMR): your changes are displayed instantly
  • Ultra-short startup time: no more waiting 30 seconds to launch the dev server
  • Optimized build: uses Rollup under the hood for efficient production builds (developed by cracks in the js ecosystem)
  • Native TypeScript support: no complicated config needed
  • Modern ecosystem: plugins, ES modules, everything you need

Setting up a React project with Vite

Prerequisites

You must have Node.js installed on your machine.

Creating the project

npm create vite@latest mon-app-react -- --template react

Installation and launch

cd mon-app-react
npm install
npm run dev

And that's it! Your React app is running on http://localhost:5173

Project structure

mon-app-react/
├── public/
│   └── vite.svg
├── src/
│   ├── assets/
│   ├── App.jsx
│   ├── App.css
│   ├── main.jsx
│   └── index.css
├── index.html
├── package.json
├── vite.config.js
└── README.md

Important files

main.jsx - The entry point

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.jsx'

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <App />
  </StrictMode>,
)

This is where it all starts. We mount our App component in the HTML element with the id root.

App.jsx - The main component

import { useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'

function App() {
  const [count, setCount] = useState(0)

  return (
    <>
      <div>
        <a href="https://vitejs.dev" target="_blank">
          <img src={viteLogo} className="logo" alt="Vite logo" />
        </a>
        <a href="https://react.dev" target="_blank">
          <img src={reactLogo} className="logo react" alt="React logo" />
        </a>
      </div>
      <h1>Vite + React</h1>
      <div className="card">
        <button onClick={() => setCount((count) => count + 1)}>
          count is {count}
        </button>
        <p>
          Edit <code>src/App.jsx</code> and save to test HMR
        </p>
      </div>
      <p className="read-the-docs">
        Click on the Vite and React logos to learn more
      </p>
    </>
  )
}

export default App

vite.config.js - Vite configuration

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
})

Resources for further learning