window.location.href vs history.pushState - which to use?

Hiroki picture Hiroki · Nov 30, 2017 · Viewed 18.1k times · Source

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.

Answer

entio picture entio · Nov 30, 2017

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.