difference between React router.push and router.replace?
Asked Answered
F

3

34

What is the difference between React router.push and router.replace?

Frampton answered 23/10, 2018 at 17:35 Comment(0)
B
41

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.

Batman answered 23/10, 2018 at 17:41 Comment(0)
R
26

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.

Roadwork answered 23/10, 2018 at 17:38 Comment(0)
B
0

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 location
  • router.push() adds to the history stack and the user can go to previous location
Bourn answered 8/7, 2024 at 6:1 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.