Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 53

Programmatic Navigation with useNavigate

Recommended resources

Hello! Welcome to our next lesson on React Router.

In our last session, we organized our product-related pages by creating a shared ProductsLayout using nested routes and the <Outlet /> component. This is a powerful pattern for keeping your UI consistent and your code DRY (Don't Repeat Yourself).

Today, we'll explore another essential routing feature: programmatic navigation. So far, we've only changed routes when a user clicks a <Link> or <NavLink>. But what if you need to redirect a user based on an action, like after they submit a form or successfully log in? This is where programmatic navigation comes in.

This concept is very similar to what you do in Laravel. When a controller method processes a form, you often end it with return redirect()->route('some.route'); to send the user to a new page. In React, we'll achieve the same result using the useNavigate hook.

By the end of this lesson, you will be able to use the useNavigate hook to redirect users programmatically in response to application events.

1. What is Programmatic Navigation?

Programmatic navigation is the act of changing the URL and rendering a new view using code, without direct user interaction with a link. It's triggered by events within your application's logic.

Common use cases include:

  • Redirecting a user to their dashboard after a successful login.
  • Navigating to a product's detail page after creating it via a form.
  • Sending a user back to the previous page after they cancel an action.

To understand the basics of how this works in React Router, let's watch a short, practical video.

Redirect with useNavigate Hook - React Tutorial 24

This video by Caleb Curry clearly introduces the useNavigate hook, explains how to set it up, and demonstrates its use within an event handler. It's a great starting point.

Please watch the following sections: Introduction (00:00 - 00:54): Understand what useNavigate is and why it's different from a Link. Setup (03:16 - 04:07): See how to import and initialize the hook. Basic Usage (04:07 - 04:49): Watch how the navigate function is called inside a button's click handler to perform a redirect.

As the video demonstrates, the process is straightforward:

  1. Import the hook: import { useNavigate } from 'react-router-dom';
  2. Get the navigate function: Inside your component, call the hook to get the navigation function: const navigate = useNavigate();
  3. Call the function: Use the navigate function with the desired path: navigate('/some-path');

2. A Practical Example: Implementing a Search Form

Let's apply this to our project. We'll add a simple form to our HomePage that lets a user search for a product. When the form is submitted, we'll programmatically redirect them to the products page with their search query in the URL.

  1. Open your src/pages/HomePage.jsx file.
  2. We'll need useState to manage the form input and useNavigate for the redirection.
  3. Replace the content of HomePage.jsx with the following:
// src/pages/HomePage.jsx
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';

const HomePage = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const navigate = useNavigate();

  const handleSearchSubmit = (e) => {
    e.preventDefault(); // Prevent the browser from reloading the page
    if (searchTerm.trim()) {
      // Navigate to the products page with the search term as a query parameter
      navigate(`/products?search=${searchTerm.trim()}`);
    }
  };

  return (
    <div style={{ textAlign: 'center', marginTop: '50px' }}>
      <h1>Welcome to Our Store!</h1>
      <p>Your one-stop shop for amazing products.</p>
      
      <form onSubmit={handleSearchSubmit} style={{ marginTop: '20px' }}>
        <input
          type="text"
          placeholder="Search for a product..."
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          style={{ padding: '8px', width: '300px' }}
        />
        <button type="submit" style={{ padding: '8px 15px', marginLeft: '10px' }}>
          Search
        </button>
      </form>
    </div>
  );
};

export default HomePage;

Now, run your app, go to the home page, type something into the search bar, and hit "Search". You'll be immediately redirected to a URL like http://localhost:5173/products?search=your-term. We aren't handling the search functionality on the products page yet, but the redirection works perfectly!


3. Advanced Navigation and Common Patterns

The navigate function can do more than just simple redirects. Let's explore some common patterns you'll encounter, especially when dealing with authentication.

Mastering the `useNavigate` Hook in React Router: A Complete Guide

This article provides excellent real-world examples, particularly for login and protected routes, which will be crucial for our e-commerce project.

Please read the following sections: "Basic Usage Example": Focus on the Login component example. This shows a very common use case: redirecting after a successful action. "Advanced Navigation Options with useNavigate": Pay close attention to the "Replace History" option. This is a critical concept for authentication flows.

Controlling Browser History with replace: true

As you read in the article, one of the most important options is { replace: true }.

Imagine a user navigates from HomePage -> LoginPage -> DashboardPage.

  • Without replace: If the user logs in and is sent to the dashboard, their browser history is [HomePage, LoginPage, DashboardPage]. If they click the browser's "Back" button from the dashboard, they'll go back to the LoginPage, which makes no sense.
  • With replace: true: When you call navigate('/dashboard', { replace: true }), the LoginPage entry in the history stack is replaced by DashboardPage. The history becomes [HomePage, DashboardPage]. Now, if the user clicks "Back" from the dashboard, they correctly return to the HomePage.

This is the standard practice for redirects after login or registration.

Navigating Back and Forward

The navigate function can also act like the browser's back and forward buttons by passing a number:

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

This is useful for creating "Cancel" buttons that return the user exactly where they came from.


Conclusion

You've now mastered a fundamental part of React Router. Programmatic navigation with the useNavigate hook gives you full control over the user's journey through your application, enabling you to build dynamic and responsive user experiences.

Key Takeaways:

  • Programmatic navigation is used to redirect users based on application logic, not just link clicks.
  • The useNavigate hook provides the navigate function to perform these redirects.
  • Common use cases include form submissions, authentication flows (login/logout), and timed redirects.
  • The { replace: true } option is essential for authentication to prevent users from navigating back to pages like login or register after they've authenticated.
  • You can navigate through the browser's history using navigate(-1) to go back.

Preview of the Next Lesson:

Our application routing is becoming quite robust. However, there's one last piece missing: what happens when a user tries to visit a URL that doesn't match any of our defined routes, like /non-existent-page? In our next lesson, we will implement a "catch-all" route to display a helpful "404 Not Found" page.