Mahamudul Hasan Rubel
HomeAboutProjectsSkillsExperienceBlogCoursesPhotosContact
Mahamudul Hasan Rubel

Senior Software Engineer crafting high-performance web applications and SaaS platforms.

Navigation

  • Home
  • About
  • Projects
  • Skills
  • Experience
  • Blog
  • Courses
  • Photos
  • Contact

Get in Touch

Available for senior/lead roles and consulting.

bd.mhrubel@gmail.comHire Me

© 2026 Mahamudul Hasan Rubel. All rights reserved.

Built with using Next.js 16 & Tailwind v4

Back to Blog
Lesson 41 of the React Fundamentals: Build Modern UIs from Scratch course
ReactJune 25, 20263 min read

Handling Browser History: Building SPA Navigation in React

Learn how to manage browser history for a smooth, single-page application feel. Master the History API to navigate React apps without full page refreshes.

ReactSPARoutingBrowser HistoryJavaScriptfrontend

Previously in this course, we focused on polishing the UI and finalizing the movie browser. While our app looks great, it currently functions as a single "page." In this lesson, we'll evolve it into a true SPA (Single-Page Application) by learning how to control the browser's URL and history stack without triggering a full page refresh.

The Problem: Why Browser History Matters

In a traditional multi-page website, clicking a link fetches a new HTML document from the server. This is slow and destroys your application's state. In an SPA, we want the user to feel like they are moving between different pages, but the browser should only render different components while keeping the JavaScript context alive.

To achieve this, we need to manipulate the window.history object. This browser API allows us to programmatically change the URL displayed in the address bar and manage the "Back" and "Forward" buttons, all without a network request.

Core Concept: The History API

The browser provides the History API, which gives us two primary methods for navigation:

  1. pushState: Adds a new entry to the browser's history stack. This is what happens when you click a link to a new page.
  2. replaceState: Modifies the current history entry. Useful for things like redirecting or updating query parameters without adding a new item to the "Back" stack.

Worked Example: Building a Manual Router

Let's implement a basic navigation handler for our movie browser. We want to navigate to a "Movie Detail" view when a user clicks a movie card.

First, we create a function to handle the URL update:

JAVASCRIPT
const navigateTo = (path) => {
  // Update the browser URL without a page reload
  window.history.pushState({}, "", path);
  
  // Create a custom event to notify our app that the URL changed
  const navEvent = new PopStateEvent("popstate");
  window.dispatchEvent(navEvent);
};

Now, we need to listen for when the user clicks the browser's back button. This triggers a popstate event:

JAVASCRIPT
import { useState, useEffect } from "react";

function AppRouter() {
  const [currentPath, setCurrentPath] = useState(window.location.pathname);

  useEffect(() => {
    const onLocationChange = () => {
      setCurrentPath(window.location.pathname);
    };

    window.addEventListener("popstate", onLocationChange);

    // Cleanup the event listener
    return () => {
      window.removeEventListener("popstate", onLocationChange);
    };
  }, []);

  // Simple routing logic
  return (
    <div>
      {currentPath === "/" && <MovieList />}
      {currentPath.startsWith("/movie/") && <MovieDetails />}
    </div>
  );
}

Hands-on Exercise

In your movie browser project, create a Link component that replaces the standard <a> tag.

  1. Create a component that accepts a to prop.
  2. Inside, render an <a> tag, but add an onClick handler.
  3. In the handler, prevent the default browser behavior with e.preventDefault().
  4. Call the window.history.pushState method to update the URL.
  5. Trigger a custom event so your AppRouter knows to update the currentPath state.

Common Pitfalls

  • Forgetting preventDefault(): If you use standard <a> tags without calling e.preventDefault(), the browser will attempt to navigate to a real server URL, causing a full page refresh and losing your app state.
  • State Desync: If you update the URL but don't update your React state (like currentPath), the UI won't re-render to show the new content. Always ensure your "router" state is the single source of truth.
  • The "Back" Button Black Hole: If you update the URL using pushState but don't listen to the popstate event, the browser's back button will change the URL in the address bar, but your app will stay stuck on the same component.

Recap

Managing browser history is the secret sauce behind the SPA experience. By using the History API, we take control of the URL, allowing for bookmarkable links and functional navigation buttons while maintaining the performance benefits of a single-page application. Understanding these routing fundamentals from scratch is critical before moving on to professional libraries like React Router.

Up next: We will tackle data persistence by learning how to use LocalStorage to save user preferences across sessions.

Previous lessonPerformance Optimization BasicsNext lesson Working with LocalStorage
Back to Blog

Similar Posts

ReactReactJune 25, 20263 min read

Fetching Data from an API: A Practical React Guide

Master the fetch API in React to retrieve external data. Learn to perform asynchronous requests and store JSON responses in your component state effectively.

Read more
ReactReactJune 25, 2026

Part of the course

React Fundamentals: Build Modern UIs from Scratch

beginner · Lesson 41 of 49

  1. 1

    Introduction to Component-Based Architecture

    4 min
  2. 2

    Understanding the Virtual DOM

    4 min
  3. 3

    Setting Up with Vite

    3 min
4 min read

Mastering useEffect Dependencies: Control Your React Lifecycle

Learn to master the useEffect dependency array to control exactly when your side effects run. Avoid infinite loops and optimize your React components today.

Read more
ReactReactJune 25, 20263 min read

Building a Movie Filter Toggle in React: A Beginner's Guide

Master the art of UI state management by adding a filter toggle to your movie app. Learn to control list rendering using boolean state and checkbox inputs.

Read more
4

Mastering JSX Syntax

4 min
  • 5

    Creating Static Components

    3 min
  • 6

    Styling Components

    3 min
  • 7

    Passing Data with Props

    3 min
  • 8

    Dynamic Movie Cards

    3 min
  • 9

    Component Composition

    3 min
  • 10

    Conditional Rendering

    3 min
  • 11

    Rendering Lists of Data

    4 min
  • 12

    The Key Prop Explained

    4 min
  • 13

    Introduction to React State

    4 min
  • 14

    Managing State with useState

    3 min
  • 15

    Building an Interactive Search Bar

    3 min
  • 16

    Handling Click Events

    4 min
  • 17

    Updating State Based on Previous State

    4 min
  • 18

    Filtering the Movie List

    3 min
  • 19

    Handling Form Submissions

    3 min
  • 20

    Controlled Components

    4 min
  • 21

    Event Bubbling and Propagation

    3 min
  • 22

    Building a Movie Filter Toggle

    3 min
  • 23

    Introduction to Side Effects

    4 min
  • 24

    useEffect Dependencies

    4 min
  • 25

    Fetching Data from an API

    3 min
  • 26

    Handling Loading States

    3 min
  • 27

    Managing Errors

    3 min
  • 28

    Cleanup Functions in useEffect

    3 min
  • 29

    Debouncing Search Input

    3 min
  • 30

    Refactoring for Clean Code

    3 min
  • 31

    Folder Structure Best Practices

    4 min
  • 32

    Extracting Custom Hooks

    3 min
  • 33

    Prop Drilling and Context API

    3 min
  • 34

    Polishing the UI

    3 min
  • 35

    Finalizing the Movie Browser

    3 min
  • 36

    Review of Component Lifecycle

    4 min
  • 37

    Review of State Management

    4 min
  • 38

    Building a Modal Component

    3 min
  • 39

    Introduction to PropTypes

    3 min
  • 40

    Performance Optimization Basics

    3 min
  • 41

    Handling Browser History

    3 min
  • 42

    Working with LocalStorage

    3 min
  • 43

    Building a Favorites List

    3 min
  • 44

    Handling Media in React

    3 min
  • 45

    Introduction to Testing

    4 min
  • 46

    Debugging React Apps

    4 min
  • 47

    Deployment Basics

    Coming soon
  • 48

    Using External Libraries

    Coming soon
  • 49

    Advanced

    Coming soon
  • View full course