Programmatic Navigation: `useNavigate`

Go beyond simple links. Learn to control your React application's flow based on user actions, API responses, and application state.

Lesson ProgressStep 1 of 11

Dashboard

Welcome, User!

Settings

Edit your settings.

0 EXP

Welcome! We're at a login screen. How do we redirect the user to a dashboard *after* they log in?

// We are at the '/login' route.
// How do we get to '/dashboard' on success?

What is Programmatic Navigation?

Programmatic navigation is the act of changing routes (pages) using JavaScript code, rather than a user clicking a standard <Link> component.

This is essential for building dynamic user experiences. Common scenarios include:

  • Redirecting a user to their dashboard after a successful login.
  • Sending a user to a "Thank You" page after a form submission.
  • Navigating to a 404 page if an API call fails to find a resource.

System Check

Which of these is an example of programmatic navigation?

Advanced Holo-Simulations

0 EXP

Log in to unlock these advanced training modules and test your skills.


Achievements

🚀
Navigation Master

Use useNavigate to successfully change routes.

🛡️
History Guardian

Correctly use { replace: true } in a login flow.

Time Traveler

Use navigate(-1) to programmatically go back.

Mission: Secure a Login Flow

Inside the `handleLogin` function, add the code to navigate to the `/dashboard` route. Crucially, you must **replace** the current page in history so the user can't go "back" to the login form.

A.D.A. Feedback:

> System integrity looks stable. Code is valid.

Challenge: Match the Action

Drag the descriptions to match the correct navigation command.

Maps('/home')
Maps('/login', { replace: true })
Maps(-1)
Go to the login page (replaces history)
Go to the home page (adds to history)
Go back one page

Challenge: Complete the Code

Fill in the missing parts to create a "Cancel" button that goes back one page.

import { } from 'react-router-dom';const = useNavigate();const handleCancel = () => { navigate(); }

Consult A.D.A.

Community Holo-Net

Peer Project Review

Submit your "Secure Login Flow" project for feedback from other Net-Runners.

Mastering React Navigation: A Deep Dive into `useNavigate`

In a modern React application, navigation isn't just about clicking links. We often need to change routes based on application logic: after a user logs in, submits a form, or an API call fails. This is called **programmatic navigation**, and in React Router v6, our primary tool for this is the `useNavigate` hook.

The Modern Way: `useNavigate` (React Router v6)

The `useNavigate` hook is a lean, powerful, and intuitive replacement for the older `useHistory` hook. Its usage is simple:

  1. Import it: import { useNavigate } from 'react-router-dom';
  2. Call it at the top level of your component: const navigate = useNavigate();
  3. Call the returned `Maps` function to change routes: navigate('/dashboard'); A
function LoginButton() {
  const navigate = useNavigate();

  function handleLogin() {
    // ... perform login logic
    navigate('/dashboard');
  }

  return <button onClick={handleLogin}>Login</button>;
}

Common Use Cases: `push` vs. `replace`

The `Maps` function can do more than just "push" a new route. By default, `Maps('/path')` acts like `history.push`, adding a new entry to the history stack. But its real power comes from its options object.

1. Login/Authentication (The `replace` use case)

When a user logs in, you don't want them to be able to click the browser's "back" button and see the login screen again. To prevent this, you can **replace** the current entry in the history stack.

Maps('/dashboard', { replace: true });

This tells React Router to replace `/login` with `/dashboard` in the history, effectively deleting the login page from the session's past.

2. Navigating Back (like `history.goBack`)

The `Maps` hook also simplifies going back and forth in history. You don't need a separate `goBack` function.

  • Go back one page: navigate(-1)
  • Go forward one page: navigate(1)
  • Go back two pages: navigate(-2)

Advanced: Passing State with Navigation

What if you want to send data to the new route without using URL params? You can pass a `state` object. This is perfect for sending a temporary message, like "You have logged out successfully," to the home page.

// In your Logout component
navigate('/', { state: { message: 'Logged out!' } });

// In your Home component
import { useLocation } from 'react-router-dom';

function Home() {
  const location = useLocation();
  const message = location.state?.message;

  return (
    <div>
      {message && <p className="success-message">{message}</p>}
      {/* ...rest of Home page */}
    </div>
  );
}

The `useLocation` hook gives you access to the `state` object you passed during navigation.

What About `useHistory`? (React Router v5)

If you are working in an older codebase (React Router v5), you will see the `useHistory` hook. It is functionally similar but with a more complex API.

  • v5: const history = useHistory(); history.push('/path');
  • v6: const navigate = useNavigate(); navigate('/path');
  • v5 (replace): history.replace('/path'); A
  • v6 (replace): navigate('/path', { replace: true });
  • v5 (go back): history.goBack();
  • v6 (go back): navigate(-1);

The `useNavigate` hook is a clear improvement, consolidating multiple methods into one, more flexible API.

Key Takeaway: Use `useNavigate` for all programmatic navigation in modern React apps. Use `Maps('/path')` for standard navigation and `Maps('/path',{ replace: true })` for scenarios like authentication where you want to modify the history stack.

React Navigation Glossary

Programmatic Navigation
The act of changing routes using JavaScript code in response to an event or logic, rather than a user clicking a `<Link>` component.
`useNavigate`
(React Router v6+) A hook that returns a function (`Maps`) which lets you programmatically navigate to different routes. This is the modern standard.
`Maps()`
The function returned by the `useNavigate` hook. You call it to trigger navigation (e.g., `Maps('/home')`).
`{ replace: true }`
An options object passed as the second argument to `Maps()`. It causes the current entry in the history stack to be replaced, instead of adding a new one.
`Maps(-1)`
A way to use the `Maps` function to move backward in the history stack, equivalent to `history.goBack()`. You can use other numbers, like `Maps(-2)`, to go back multiple steps.
History Stack
A list maintained by the browser (or React Router) of the pages visited. `Maps` adds to this stack, while `replace` modifies it.
`useHistory`
(React Router v5) The legacy hook for programmatic navigation. It returned a `history` object with methods like `push()`, `replace()`, and `goBack()`. Superseded by `useNavigate`.
`useLocation`
A hook that returns a `location` object containing information about the current URL, including `pathname`, `search` (query params), and `state` (data passed via navigation).

About the Author

Author's Avatar

TodoTutorial Team

Passionate developers and educators making programming accessible to everyone.

This article was written and reviewed by our team of web development experts, who have years of experience teaching React and building complex, single-page applications.

Verification and Updates

Last reviewed: October 2025.

We strive to keep our content accurate and up-to-date. This tutorial is based on the latest React Router v6 specifications and is periodically reviewed to reflect industry best practices.

External Resources

Found an error or have a suggestion? Contact us!