In the React Router library, BrowserRouter and Router (more specifically, variants of Router such as BrowserRouter, HashRouter, etc.) are different components used for building routing systems in single-page applications. Below, I will explain their main differences:
BrowserRouter
BrowserRouter is a higher-level component of React Router that uses the HTML5 history API (such as pushState, replaceState, and popstate events) to keep the UI and URL in sync. When using BrowserRouter, the URL displays the actual path, for example:
shellhttps://yoursite.com/about https://yoursite.com/home
This approach provides very clean and intuitive URLs, which is highly beneficial for applications requiring search engine optimization (SEO).
Example
jsximport { BrowserRouter as Router, Route, Link } from "react-router-dom"; function App() { return ( <Router> <div> <nav> <Link to="/">Home</Link> <Link to="/about">About</Link> </nav> <Route path="/" exact component={Home} /> <Route path="/about" component={About} /> </div> </Router> ); }
Router (more accurately, variants of the Router component)
Router is a basic routing component that does not automatically apply any history implementation; instead, it allows you to pass your own history object. This approach provides greater customization but requires more configuration. Common variants of Router include BrowserRouter, HashRouter (which uses the URL's hash portion to maintain UI state), and MemoryRouter (which stores the URL history in memory and does not display it in the address bar).
Example
jsximport { Router, Route, Link } from "react-router-dom"; import { createBrowserHistory } from "history"; const customHistory = createBrowserHistory(); function App() { return ( <Router history={customHistory}> <div> <nav> <Link to="/">Home</Link> <Link to="/about">About</Link> </nav> <Route path="/" exact component={Home} /> <Route path="/about" component={About} /> </div> </Router> ); }
Summary
Using BrowserRouter is the simplest approach and is suitable for most web applications. Directly using Router with a custom history object is appropriate when more control is needed or when you need to work with specific history handling methods.
I hope this explains the differences and use cases of BrowserRouter and Router in React Router!