Different types of Router

There are three types of Router,

  • Memory Router
  • Hash Router
  • Browser Router - Modern browsers support normal URL in the client-side using

Memory Router

Route URL won't be shown in the browser URL tab. It will be computed and stored only on the browser memory.

This is used when the URLs don't need to be shown to the end-user. For example, rendering the website on a web-view in a mobile application.

It is not used widely for most use cases unless the device has limitations. Or the web app has such requirements to not show the URL to the end-user on the browser.

Our example with MemoryRouter will be,

Hash Router

There will be # in the URL. The URL after # will be used to match the path in the client-side application (i.e., React app).

Example, https://jsmates.com/#/about

Here, https://jsmates.com will be served from the server. And then, the front end React app on the browser will handle the /#/about URL. The react-router will load the appropriate page.

If you need to support old browsers in your application, then you need to use HashRouter.

Our example with HashRouter will be,

Browser Router

Browser Router is the most used router in React apps. Most modern browser support HTML pushState. Using the pushState API, you can support a clean URL on the client-side.

Example, https://jsmates.com/about

The trick here is, The server needs to serve the React app on all URL routes. Then, the React router will match the URL in the frontend and load the content.

Pseudo code of the server to serve the frontend app on all routes will be like this,

// Server same HTML for all routes
app.get('*', (req, res) => {
  return res.sendFile('./index.html');
  // This `index.html` file loads the React application
});

Then, React in the frontend will take care of checking the URL and load appropriate content based on it.

If you need to support only the modern browser, then the best bet is BrowserRouter.

Depends on the use case, developers select different Routers. We are using BrowserRouter in our examples.

Our latest example with BrowserRouter, play around the code,