What is the difference between React router.push and router.replace?
The router history works like a stack
of routes
. When you use the router.replace
, you're overwritting the top of the the stack. When using the router.push
, it adds a new route to the top of the stack
.
The router history allows you to go back to the last page. For example, when the user navigates to a invalid route, you can use the router.replace
to prevent the user to navigate back to the invalid route.
The history of pages you visit in your web browser is like a stack
data structure. You can either push
a new record onto the top of the history stack or you can replace
the top record. If you use push
, and then hit the browser's back button, it will take you back to the page you are currently on, but if you use replace
it will take you two pages back.
Similarities
- Both change th url of the adress bar to the new route
- Both will take your user to the new location
Differences
router.replace()
will prevent the user from going back to previous page.router.back()
will not place the user to the previous locationrouter.push()
adds to the history stack and the user can go to previous location
© 2022 - 2025 — McMap. All rights reserved.