Pushstate and Replacestate: What You Need to Know

Pushstate and Replacestate: What You Need to Know

pushState() In an HTML document, the history. pushState() method adds an entry to the browser’s session history stack.

The big difference is, that while pushState will create a new entry in the browser’s history, replaceState will only replace the current state. As a side effect of this, using the replaceState method will change the URL in the address bar, without creating a new history entry.

pushstate and replacestate

Here’s the syntax of the pushState() method:

history.pushState(state, title, [,url])

The pushState() method accepts three parameters:

  1. state
  2. title
  3. url


window.history.pushState() adds new entries to the users’ history.

If you were to use pushState() three times, a user would have to press ‘back’ in their browser three times to get to where they started.

If your browser’s history were implemented using the History Web API, this method would be used when users click a regular link to visit a new page.

When to use pushState

  • the majority of the content on page has been updated
  • if you would give the page a different <h1> or <title>


window.history.replaceState() changes the current history entry.

If you were to use replaceState three times, a user would only have to press back once.

You may decide that you want to keep a user’s state the same when they go ‘back’ to a page, but without adding or changing the history. In these cases, you could consider sessionStorage.

When to use replaceState

  • most of the content on the page is the same
  • you want to keep a component in the same state it was when a user decides to come ‘back’ to the page. (See accordions and tabs)
  • the user’s action changes the shape of the data, for example re-ordering a data table or filtering a data table.

You will be using replaceState it more often since it tends to work better with components.