While working with React routers (Router, BrowserRouter, HashRouter, MemoryRouter), you ask yourself this question, which one should you select for your application.
I have a good share of experience with routers and i follow below simple rules to choose:
If you want to implement scenario based navigation on button click, then go with programmatic navigation by writing
history.push('/path')
. For this purpose, Router tag is suitable.If you don't have programmatic navigation and want URL to change in Browser's URL bar/Search bar then go with BrowserRouter, for ex- abc.com/home, abc.com/dashboard
If you want the URL to be static and not change then go with MemoryRouter. This way, you are not exposing URLs to outside world. Plus, MemoryRouter is meant for non-browser environments like Web apps that open in Mobile Webview.
Probably, you have observed that many websites' URL have # after domain name and then the remaining URL. The reason is that if you are working with a static application and don't want your app to make a server side request for navigation and navigating within the HTML content. Well, if you want to implement the same, use a HashRouter.
Top comments (2)
are you sure? I thought
BrowserRouter
hashistory.push()
in V5 ornavigate()
in V6Thanks @sunflower for your comments. When i wrote the article more than 2yrs ago, i believe history.push was not available with BrowserRouter with the version i have used. I may be wrong and thanks for pointing out as this article needs to be updated by considering latest React router versions. I will do it in the near future.