A single-page application (SPA) loads one HTML page and then swaps components on the screen without full page reloads; in React this is done by creating a React app and adding client-side routing with React Router.
Steps
- Create the project (Vite or Create React App):
npm create vite@latest my-spa -- --template react cd my-spa npm install npm install react-router-dom - Create page components, e.g.
Home.jsx,About.jsx,Contact.jsx:export default function Home() { return <h2>Home Page</h2>; } - Set up routes in
App.jsx:import { BrowserRouter, Routes, Route, Link } from "react-router-dom"; import Home from "./Home"; import About from "./About"; import Contact from "./Contact"; export default function App() { return ( <BrowserRouter> <nav> <Link to="/">Home</Link> |{" "} <Link to="/about">About</Link> |{" "} <Link to="/contact">Contact</Link> </nav> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> <Route path="/contact" element={<Contact />} /> </Routes> </BrowserRouter> ); } - Run it:
npm run dev, and build for deployment withnpm run build.
How it works. The server sends one index.html. <Link> changes the URL using the browser History API without reloading; <Routes> picks the matching <Route> and React renders only that component. Data is fetched from APIs (e.g. with fetch in useEffect) and shown by updating state.
Benefits: fast navigation, app-like feel, less server load. Drawbacks: larger first load and weaker SEO unless server rendering is added.