SPA concepts
| Routes as state | |
| Render functions | |
| Load JSON | |
| Back button note |
Routes as state
A single page app keeps one page shell and swaps content inside it. The current route is plain state, often just a string such as home or about, that decides which screen to show.
Treat routes as data first and address bar second. When state drives the screen, navigation becomes a simple assignment followed by a render.
type Route = "home" | "about";
let route: Route = "home";
route = "about";
Render functions
Each screen is a function that returns an HTML string for the current state. The shell assigns that string to the page and the visible content updates at once.
Pure render functions are easy to preview and test because the same input always yields the same markup. Events and loading live outside, rendering stays dumb and honest.
function renderHome(): string {
return "<h1>Home</h1>";
}
function render(next: string): void {
document.body.innerHTML = next;
}
render(renderHome());
Load JSON
Most screens need server data, usually fetched as JSON after navigation. Load with a typed helper, wait for the answer, then pass the result into the render function.
Show a loading line first so the app never looks frozen. Empty, loading, ready, and failed are four honest states worth rendering on purpose.
type User = { name: string };
async function loadUser(id: string): Promise<User> {
const res = await fetch("/users/" + id);
return res.json() as Promise<User>;
}
Back button note
Users expect the browser back button to undo navigation, not to break the app. Sync route state with history so back and forward move between screens you already render.
Start simple: one listener that reads the new location and renders again. Deep linking then works for free because every route is just state your render already knows.
window.addEventListener("popstate", () => {
render(renderHome());
});
Next: Typed API client
Article author: Arthur Isaev