DEV Community

vishwa v
vishwa v

Posted on

react-7

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;

Enter fullscreen mode Exit fullscreen mode

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";
Enter fullscreen mode Exit fullscreen mode

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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)