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
- URL Structure:
BrowserRouteruses clean paths (e.g.,/dashboard), whereasHashRouteruses hash paths (e.g.,/#/dashboard). - Server Configuration:
BrowserRouterrequires server-side configuration. If a user refreshes the page on/dashboard, the server must be configured to redirect that request back toindex.html.HashRouterrequires zero server configuration because the server only ever sees the root URL. - SEO Impact: Clean URLs used by
BrowserRouterare significantly better for Search Engine Optimization (SEO). Search engines do not always index or crawl content hidden behind hash symbols effectively.
When to Use HashRouter
While BrowserRouter is the recommended router for most
modern web applications, HashRouter is highly useful in the
following scenarios:
- 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,
HashRouterprevents “404 Not Found” errors on page refreshes. - Legacy Web Servers: If you are deploying to an
older web server where you do not have administrative access to
configure URL rewriting,
HashRouteris the easiest workaround. - Desktop Applications: When building desktop
applications using frameworks like Electron, where files are loaded
locally from the file system (
file://),HashRouteris often necessary to handle routing correctly.