Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-router: Why the preference for browserHistory over hashHistory?

Tags:

react-router

I'm relatively new to React; apologies if this is a really naive question.

What are the technical advantages to browserHistory that make it preferable over hashHistory? For example, is there a major performance/efficiency boost from it using the History API?

The docs state that browserHistory is recommended, even though this comes at the cost of the additional server config and needing to hard-code or configure your base URL for different servers via basename.

hashHistory "just works", however, regardless of the base URL from which the files are served. No server config needed. Bundle your app, host it from any URL/path on a server, good to go.

It might be good if the docs went a bit further in explaining why it browserHistory is recommended even though it involves more complexity.

like image 633
Clint Harris Avatar asked Jan 26 '16 13:01

Clint Harris


People also ask

What is Browserhistory react router?

React Router uses the history package, which builds on the browser history API to provide an interface to which we can use easily in React apps. location - (object) The current location. May have the following properties: pathname - (string) The path of the URL.

What is HashRouter react?

We can start looking at the React HashRouter and its applications. A Router that uses the hash portion of the URL (i.e. window.location.hash) to keep your UI in sync with the URL. (


1 Answers

In some cases hashHistory is fine - except when you start dealing with server-side logic that needs to know a full URL of the original request.

Browsers do not send the #hash part of URL in any of HTTP requests.

Therefore server-side (i.e. NodeJS) would not know what #hash was in the URL when user requested a page.

A good example is user trying to load a page that requires a login (via oAuth etc.). Before user is taken to a separate website for authentication, you app's server-side would tell the authentication vendor what URL redirect user to after a successful login (usually it is to the original URL requested as most websites do this). If you were to use hashHistory - server-side would know only the bits before # symbol and would redirect user to the main page of your app and not a sub-page that user wanted to load.

I hope that makes sense.

like image 56
Romasato Avatar answered Nov 26 '22 12:11

Romasato