Skip to main content

Command Palette

Search for a command to run...

history.push() vs history.replace()

Updated
2 min read
history.push() vs history.replace()

The useHistory is a Hooks API which exposes a functionality to perform redirect by making use of the history object.

If you want the user to be able to use the browser's back button come back to the current webpage; use push().

If you don't want the user to be able to use the browser's back button come back to the current webpage; use replace(). Because the current webpage won't be he browser's history stack.

The useHistory hook:

The name might be a bit strange, but it's named like this because it allows us to change the browser history. So the history of pages we visited. We call useHistory like this, and that gives us a history object, which we can store in a constant. And extend this history object, which we can use to trigger certain history changing actions. And what changes the history of pages, well, for example if we add a new page, if we go to a new page. And we can navigate around with the push method here, which pushes a new page on the stack of pages, so a new page on our history of pages, or we can navigate with the replace method that replaces the current page. The difference is that with push, we can go back with the back button to the page we're coming from, with replace we can't.

So replace is like a redirect where we changed occurred page, push adds a new page. And it's up to you what you want. Do you want to allow your user to go back or not Here I'll go for push and I will allow the user to go back, and then here we could go to /quotes like this.

import React from 'react'
import QuoteForm from '../components/quotes/QuoteForm';
import { useHistory } from 'react-router-dom';

function NewQuote() {

    const history = useHistory();

    const addQuoteHandler = (quoteData) => {
        console.log(quoteData);

                                                         // here
        history.push('/quotes');
    }


    return (
        <QuoteForm onAddQuote={addQuoteHandler} />
    )
}

export default NewQuote

More from this blog

Omar's blog

135 posts

history.push() vs history.replace()