DEV Community

Bikram Singh Patel
Bikram Singh Patel

Posted on

React Routers! Which one should you choose?

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:

  1. 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.

  2. 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

  3. 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.

  4. 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)

Collapse
 
sunflower profile image
sunflowerseed

are you sure? I thought BrowserRouter has history.push() in V5 or navigate() in V6

Collapse
 
bkrmsp profile image
Bikram Singh Patel

Thanks @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.