Skip to main content

Command Palette

Search for a command to run...

22) Browser Router

Updated
View as Markdown
  1. Browser Router
    The Browser Router is a core part of routing in React applications. It enables navigation between different pages without reloading the browser, giving you a true Single Page Application (SPA) experience.
    BrowserRouter is a component that,
    i) Uses the browser’s History API
    ii) Keeps UI in sync with the URL
    iii) Enables client-side routing
    It lets your React app behave like a multi-page website without actually reloading pages.

  2. How It Works Internally
    BrowserRouter uses HTML5 History API.
    This allows, Changing URL (/home → /about) Without refreshing the page While React updates only required components.

    import {
      BrowserRouter,
      Routes,
      Route,
      Link
    } from "react-router-dom";
    
    const Home = () => {
      return <h2>Home Page</h2>;
    }
    
    const About = () => {
      return <h2>About Page</h2>;
    }
    
    const App = () => {
      return (
        <BrowserRouter>
          <nav>
            <Link to="/">Home</Link> | 
            <Link to="/about">About</Link>
          </nav>
    
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/about" element={<About />} />
          </Routes>
        </BrowserRouter>
      );
    }
    

    This enables routing across your app.

  3. Key Features of Browser Router
    i) Clean URLs

    /home
    /about
    /products
    

    ii) No Page Reload
    Faster navigation
    Better user experience
    iii) Back/Forward Support
    Browser buttons work naturally
    iv) Dynamic Routing

    <Route path="/user/:id" element={<User />} />
    

    BrowserRouter enables SPA navigation
    Uses History API (no reload)
    Wraps your app to enable routing Works with: Routes, Route, Link.
    BrowserRouter keeps UI in sync with URL using the browser history API, enabling client-side routing without page reloads.

  4. Advantages of BrowserRouter
    i) Enables Single Page Application (SPA) Navigation
    With BrowserRouter, users can move between pages without reloading the browser.
    ii) Uses Clean URLs
    BrowserRouter creates clean and readable URLs like /about, /profile, /products. Instead of /#/about
    iii) No Full Page Reload
    iv) Supports Browser History Navigation
    v) Better User Experience
    vi) Dynamic Routing Support
    vii) Nested Routing Support