Single Page Applications (SPA)
Overview
Traditional websites request a brand new HTML page from the server every time you click a link, causing the screen to flash white and reload completely. React apps are typically 'Single Page Applications' (SPAs). You only ever download one single HTML file (`index.html`). When you click a link in an SPA, React intercepts the click, prevents the server request, and instantly swaps out the components on the screen using JavaScript. This makes the app feel as fast and seamless as a native mobile app.
Syntax
Because there are no actual page reloads, any state you have living high up in your app (like a user's login session or items in a shopping cart) persists seamlessly as they navigate around.
// In a traditional app, clicking <a href="/about"> requests 'about.html' from the server.
// In a React SPA, the URL changes to '/about', but no request is made.
// React simply says: "Oh, the URL changed? I will unmount the <Home> component and mount the <About> component right here."Common Pitfalls
- Using standard `<a href="/page">` tags in a React app. This defeats the entire purpose of an SPA because it forces the browser to do a hard refresh. You must use Router-specific `<Link>` components instead.
Interview Tips
- Understand the trade-offs of SPAs. Pros: Blazing fast navigation, great UX, persistent state. Cons: Slower initial load time (because you download a massive JS bundle upfront), and historically poor SEO (though modern frameworks like Next.js solve this).
Real-World Example
Music players like Spotify or video sites like YouTube. Notice how the music keeps playing uninterrupted even as you click around different artist pages. That is the power of an SPA.
function App() {
return (
<BrowserRouter>
{/* The persistent AudioPlayer lives OUTSIDE the Routes! */}
{/* It will never unmount or reload when the user navigates. */}
<AudioPlayer />
<main>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/artist/:id" element={<Artist />} />
</Routes>
</main>
</BrowserRouter>
);
}