What is HashRouter in React Router

This article provides a clear overview of HashRouter in React, explaining how it works, when to use it, and how it differs from other routing solutions like BrowserRouter. You will learn how HashRouter leverages the URL hash to manage application state and why it remains a valuable tool for specific hosting environments.

Understanding HashRouter

HashRouter is a router component provided by the React Router library. It uses the hash portion of the URL (everything after the # symbol, such as http://example.com/#/about) to keep your application’s user interface in sync with the URL.

When a user navigates to a new route in a HashRouter application, the browser does not send a request to the web server for a new page. Instead, it updates the hash segment of the URL, which triggers a client-side event that React Router listens to, allowing it to render the correct component instantly.

How HashRouter Works

In standard web browsers, any request made to a server ignores the hash portion of the URL. For example, if a user requests https://myapp.com/#/dashboard, the browser only requests https://myapp.com/ from the hosting server.

Once the server delivers the main index.html file and the React application loads, React Router reads the hash (#/dashboard) from the window location. It then matches this hash pattern to the corresponding route defined in your code and renders the appropriate component.

Key Differences: HashRouter vs. BrowserRouter

When to Use HashRouter

While BrowserRouter is the recommended router for most modern web applications, HashRouter is highly useful in the following scenarios:

  1. Static File Hosting: If you are hosting your React app on platforms like GitHub Pages, GitLab Pages, or basic AWS S3 buckets where you cannot configure redirect rules for deep links, HashRouter prevents “404 Not Found” errors on page refreshes.
  2. Legacy Web Servers: If you are deploying to an older web server where you do not have administrative access to configure URL rewriting, HashRouter is the easiest workaround.
  3. Desktop Applications: When building desktop applications using frameworks like Electron, where files are loaded locally from the file system (file://), HashRouter is often necessary to handle routing correctly.