How to Implement useNavigate Hook in React

The useNavigate hook is a powerful feature introduced in React Router v6 that allows you to navigate programmatically within your React applications. This article provides a straightforward guide on how to set up, initialize, and use the useNavigate hook to redirect users, pass state between routes, and handle browser history.

Prerequisites

To use the useNavigate hook, you must have React Router v6 installed in your project. You can install it using npm:

npm install react-router-dom

Ensure that your component tree is wrapped in a <BrowserRouter> component, typically inside your root entry file (such as main.js or index.js).

Basic Implementation

To implement the hook, import it from react-router-dom inside a functional component, call it to obtain the navigate function, and then trigger it within an event handler or a useEffect hook.

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

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

  const handleNavigation = () => {
    navigate('/about');
  };

  return (
    <div>
      <h1>Home Page</h1>
      <button onClick={handleNavigation}>Go to About Page</button>
    </div>
  );
}

export default Home;

Advanced Use Cases

1. Replacing the History Entry

By default, navigating to a new path pushes a new entry onto the history stack. If you want to redirect the user and replace the current entry in the history stack—preventing them from returning to the previous page when clicking the browser’s back button—pass an options object with replace: true.

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

2. Passing State to the Destination Route

You can send temporary data to the target route by passing a state key inside the options object.

navigate('/profile', { state: { userId: 101, admin: true } });

To access this state on the receiving component, use the useLocation hook:

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

function Profile() {
  const location = useLocation();
  const { userId, admin } = location.state || {};

  return (
    <div>
      <p>User ID: {userId}</p>
      <p>Role: {admin ? 'Admin' : 'User'}</p>
    </div>
  );
}

3. Going Back or Forward in History

You can navigate backward or forward through the browser’s session history by passing a positive or negative integer representing the number of steps.

// Go back to the previous page
navigate(-1);

// Go forward one page
navigate(1);