Conceptual Question

How does the window.history API work?

React Ecosystem

How does the window.history API work?

JavaScript

The short answer

The window.history API lets you manipulate the browser's session history — the list of pages the user has visited in the current tab. You can go back, go forward, and add or replace entries without a page reload. This is the API that React Router and other client-side routers use to handle navigation in SPAs.

Basic navigation

JAVASCRIPT
1history.back(); // same as clicking the back button
2history.forward(); // same as clicking the forward button
3history.go(-2); // go back 2 pages
4history.go(1); // go forward 1 page

pushState — add a new history entry

JAVASCRIPT
1history.pushState(
2 { page: 'about' }, // state object (any serializable data)
3 '', // title (ignored by most browsers)
4 '/about' // new URL
5);

This does three things:

  1. Changes the URL in the address bar to /about
  2. Adds a new entry to the history stack
  3. Does NOT reload the page or make a network request

The user can now hit the back button to go to the previous URL.

replaceState — replace the current entry

JAVASCRIPT
1history.replaceState({ page: 'home' }, '', '/home');

Same as pushState, but it replaces the current history entry instead of adding a new one. The user cannot go back to the previous URL because it was replaced.

The popstate event

When the user clicks back or forward, the popstate event fires:

JAVASCRIPT
1window.addEventListener('popstate', (event) => {
2 console.log('Navigation happened');
3 console.log(event.state); // the state object from pushState
4 // Update the UI based on the new URL
5 renderPage(window.location.pathname);
6});

This is how SPAs handle browser navigation. When the user clicks back, the SPA listens for popstate, reads the new URL, and renders the appropriate page without a full reload.

How React Router uses it

React Router uses pushState when you navigate and popstate to detect back/forward clicks:

JAVASCRIPT
1// When you click a Link, React Router calls:
2history.pushState(null, '', '/dashboard');
3// Then renders the Dashboard component
4
5// When user clicks back, React Router listens for popstate
6// and renders the previous route's component

Interview Tip

Explain pushState (adds entry, changes URL, no reload) and popstate (fires on back/forward). Connecting it to how React Router works shows you understand the internals of client-side routing, not just the API surface.

Why interviewers ask this

The History API is the foundation of client-side routing. Interviewers ask about it to see if you understand how SPAs handle navigation. If you have ever wondered how React Router changes the URL without a page reload, this is the answer.

Continue with nearby questions from the same topic cluster.