What is BrowserRouter?
BrowserRouter is a wrapper component from react-router-dom.
It uses the HTML5 history API (pushState, replaceState) to keep your UI in sync with the URL.
In simple terms: it tells React Router to use the browserβs normal URL system for navigation.
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "./Home";
import About from "./About";
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
);
}
export default App;
When to Use
Always use BrowserRouter for modern web apps unless you specifically need HashRouter (for static file hosting without server-side support).
Itβs the standard choice for React projects with proper server setup.
What is useNavigate?
useNavigate is a hook from React Router v6.
It lets you programmatically navigate between routes (instead of using or ).
Think of it as a function you call to change the URL and move to another page.
How to Use It
Import the Hook
jsx
import { useNavigate } from "react-router-dom";
Get the Navigate Function
jsx
function Home() {
const navigate = useNavigate();
const goToAbout = () => {
navigate("/about");
};
return (
<div>
<h1>Home Page</h1>
<button onClick={goToAbout}>Go to About</button>
</div>
);
}
When you click the button, React Router changes the route to /about
When to Use useNavigate
After a form submission (e.g., redirect to dashboard).
After authentication (e.g., redirect to login if not logged in).
For conditional navigation (e.g., if user doesnβt have access, send them elsewhere).
Top comments (0)