Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
77
rated 0 times [  80] [ 3]  / answers: 1 / hits: 44273  / 7 Years ago, thu, november 30, 2017, 12:00:00

I've been teaching myself react-router, and now I'm wondering which method should be used for going to another page.



According to this post (Programmatically navigate using react router), you can go to another page by this.props.history.push('/some/path').



Honestly, however, I'm not quite sure about the differences between window.location.href and history.pushState.



As far as I understand, window.location.href = /blah/blah; leads you to anther page by making a new HTTP call, which refreshes the browser.



On the other hand, what history.pushState (and this.props.history.push('/some/path')) does is to push a state. This, apprently, changes HTTP referrer and consequently updates XMLHttpRequest.



Here is an excerpt from mozila's documentation...




Using history.pushState() changes the referrer that gets used in the HTTP header for XMLHttpRequest objects created after you change the state.




To me, it sounds like both methods make a new HTTP call. If so, what are the differences?



Any advice will be appreciated.



PS



I thought that developers would need to consider whether it's necessary to get data from the server, before deciding how to go to another page.



If you need to retrieve data from the server, window.location.href would
be fine, since you'll make a new HTTP call. However, if you are using <HashRouter>, or you want to avoid refreshing you page for the sake of speed, what would be a good approach?



This question led me to make this post.


More From » window

 Answers
24

history.pushstate does not make a new HTTP call (from mozilla doc quoted by you):




Note that the browser won't attempt to load this URL after a call to pushState(), but it might attempt to load the URL later, for instance after the user restarts the browser.




window.location.href = url navigates the browser to new location, so it does make a new http request. Note: exception is the case when you specify new url as hash fragment. Then window is just scrolled to corresponding anchor






You can check both running them from devTools console having Network tab open. Be sure to enable preserve log option. Network tab lists all new http requests.


[#55796] Monday, November 27, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
breap

Total Points: 606
Total Questions: 96
Total Answers: 108

Location: Djibouti
Member since Sun, Feb 27, 2022
2 Years ago
breap questions
Thu, Jun 24, 21, 00:00, 3 Years ago
Wed, Mar 18, 20, 00:00, 4 Years ago
Mon, Oct 7, 19, 00:00, 5 Years ago
;