Course contentsShow
← React
Lesson 1858 of 2,39643. RoutingFree lesson

Replace vs Push: Controlling Browser History

Use replace option to prevent back-button issues when redirecting after actions like login.

Replace vs Push: Controlling Browser History

You'll learn how to use the replace option to prevent unwanted back-button behavior after redirects.

The Problem with Default Navigation

When you navigate programmatically with useNavigate(), React Router by default pushes a new entry onto the browser's history stack. This means the user can click the back button to return to the previous page—which is usually what you want. But not always.

Consider a login flow: after a user successfully logs in, you redirect them to the dashboard. If they hit the back button, should they land back on the login page? Probably not—they're already authenticated! This creates a confusing loop where the login page might auto-redirect them forward again.

Using the Replace Option

The replace option tells React Router to replace the current history entry instead of adding a new one:

import { useNavigate } from 'react-router-dom';

function LoginPage() {
  const navigate = useNavigate();

  const handleLogin = async (credentials) => {
    await loginUser(credentials);
    // Replace the login page in history
    navigate('/dashboard', { replace: true });
  };

  // ... rest of component
}

Now when the user reaches the dashboard, the login page is no longer in their history stack. Clicking back takes them to wherever they were before the login page.

When to Use Replace

Use replace: true for:

  • Post-login/logout redirects
  • Form submission success redirects
  • Error page redirects
  • Any redirect where returning to the previous page doesn't make sense

Use the default (push) for:

  • Normal user-initiated navigation
  • Clicking links or buttons that should be reversible

Key Takeaway: Use { replace: true } with navigate() to replace the current history entry instead of adding a new one, preventing back-button issues after actions like login or form submissions.