Search code examples
reactjs

What is the purpose of routers?


I'm in the planning phase of building a web app. I keep seeing the concept of a "router" getting thrown around. And so far the reasoning has been:

  1. You need a router to get the back button
  2. You need a router to add navigation to your application
  3. Your users will be unhappy if you don't have a router

The problem I'm running into is that I'm not getting good explanations of the why. Why can't I just link directly to my webpage? I swear I've built apps where I have my index.html link to my_other_page.html and then been able to click the back button on my browser with everything working.

What am I missing?


Solution

  • Href, Hyperlinking, or hard navigation whatever you can call them. The notion of hard navigating pages like when you change from /home.html to /about-us.html, requires a full page refresh. You'll see a split-second blank white screen since the browser resets itself and start fetching the relevant data from a clean slate.

    React Router works the opposite. Literally every page you visit (/, /about-us, or anything) is the same index.html. React Router fetch the whole website's information once and try to check what page you are trying to navigate and will try to optimize any rendering possible. You can call this as "soft navigation" since you are not actually changing the page but the React Router made you feel like you went to a different page.

    This concept is called Single Page Application (SPA) since your website is literally a single page.

    Try comparing between soft navigation and hard navigation and you'll see a clear difference.

    Soft Navigation:

    const navigate = useNavigate()
    
    navigate("/page")
    

    Hard Navigation:

    windows.location.href("/page")