What is the trade off between history push and replace?
Asked Answered
H

4

86

I use History package to redirect invalid URL to 404 page on my react component.

I use .replace instead of .push simply because I don't want the browser to record any invalid url I have visited.

Have I missed the point here? And is there a trade-off between choosing one or the other for my purpose?

Can someone explain to me? thanks in advance ;)

Hennery answered 6/9, 2016 at 3:14 Comment(0)
L
78

I think you have the right idea.

I personally use .replace when redirecting from an invalid url (or non relevant, i.e. redirect to "profile" page when a logged user goes to the "/login" url), so using the browser's "back" button works properly for the end user.

Luannaluanne answered 6/9, 2016 at 3:28 Comment(0)
T
26

router.replace acts like router.push, the only difference is that it navigates without pushing a new history entry, as its name suggests - it replaces the current entry.

Talishatalisman answered 19/3, 2018 at 14:1 Comment(0)
L
14

I like to use .replace() when i have a definitive action and i dont want the user to be able to come back to this page.

Example: i have a product detail page with a delete button to ultimately deletes the product. When i click the button i do router.replace back to the list of all products so when the user uses the back button in the browser he is not able to go back to the details page so he cannot see or even click again the delete button as this product does not exist anymore.

Legislature answered 28/1, 2021 at 8:27 Comment(0)
R
3

To put it in brief, if you think of the history as an array of visited locations, push() will add a new location to the array and replace() will replace the current location in the array with the new one.

enter image description here

Reparable answered 20/2 at 9:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.