Single Page Application (SPA)

What is an SPA?

A Single Page Application loads one HTML page and a JavaScript bundle once. After that, JavaScript changes the content and the URL without reloading; only data (JSON) is fetched from the server.

First visit  →  index.html + app.js
Click "About" →  JavaScript swaps the component, URL becomes /about (no reload)
Need data     →  fetch('/api/about')  →  JSON

Examples: Gmail, Google Maps, Trello, most React apps.

An SPA in Miniature

Example

Clicking a tab changes what is shown without loading a new page. React Router does the same thing with real URLs.

import { useState } from 'react';

const pages = {
  home: <p>Welcome to the home page.</p>,
  about: <p>We teach React with live examples.</p>,
  contact: <p>Mail us at hello@example.com</p>,
};

export default function App() {
  const [page, setPage] = useState('home');
  return (
    <div>
      {Object.keys(pages).map((name) => (
        <button key={name} onClick={() => setPage(name)}
          style={{ fontWeight: page === name ? 'bold' : 'normal' }}>
          {name}
        </button>
      ))}
      {pages[page]}
    </div>
  );
}

Result