CodeBlanks Logo Icon CodeBlanks

replaceState

JavaScript course · Advanced · Lesson 80/100

Learn to replace the current history entry with replaceState.

What is replaceState?

history.replaceState(state, unused, url) takes the same three parameters as pushState, but it does not add a new history entry. Instead, it updates the state and URL of the current entry.

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

The back button still goes to the previous entry, because replaceState overwrites the current entry rather than adding a new one.

pushState versus replaceState

Both methods change the URL and state, but they affect history differently.

history.pushState({page: 'a'}, '', '/a');
// history: [home, a]
history.replaceState({page: 'b'}, '', '/b');
// history: [home, b]

pushState adds a new entry; the back button goes to the previous entry. replaceState overwrites the current entry; no new entry is added to history.

Exercise Update the entry with replaceState

Assign 'settings' to a currentTab variable. Call history.replaceState with the state { tab: currentTab }, an empty title and the URL '/settings'.

Show example solution
const currentTab = 'settings';
history.replaceState({ tab: currentTab }, '', '/settings');

Test yourself

  1. Complete the replaceState call

    const state = { tab: 'settings' };
    ____;
    Show answer
    const state = { tab: 'settings' };
    history.replaceState(state, '', '/settings');
  2. When do you use replaceState instead of pushState?

    • When you want to add a new history entry
    • When you want to change the current entry and prevent the back button from adding a new one
    • When you want to reload the page
    • When you want to clear history entirely
    Show answer

    When you want to change the current entry and prevent the back button from adding a new one — Correct! replaceState updates the current entry instead of adding a new one.

  3. pushState versus replaceState

    pushState
    adds a new entry
    replaceState
    changes the current entry
    back button
    goes to the previous entry
    state object
    data stored with the entry

All lessons in Advanced