How to Update and Use useNavigate Hook in React

This article explains how to transition to and use the useNavigate hook in React Router v6. You will learn how to replace the deprecated useHistory hook, perform programmatic navigation, update browser history states, and redirect users efficiently within your React applications.

Upgrading from useHistory to useNavigate

In React Router v6, the useHistory hook was deprecated and replaced by the useNavigate hook. If you are upgrading your application, you must update your import statements and navigation calls.

Here is how the syntax changed:

React Router v5 (useHistory):

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

function MyComponent() {
  const history = useHistory();
  
  const handleClick = () => {
    history.push('/dashboard');
  };
}

React Router v6 (useNavigate):

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

function MyComponent() {
  const navigate = useNavigate();
  
  const handleClick = () => {
    navigate('/dashboard');
  };
}

Common Navigation Patterns with useNavigate

The navigate function returned by the hook is highly versatile and handles several different routing behaviors depending on the arguments you pass to it.

1. Basic Navigation

To navigate to a specific path, pass the target URL string as the first argument:

// Navigate to an absolute path
navigate('/profile');

// Navigate to a relative path
navigate('../settings');

2. Replacing the Current History Entry

If you want to update the route but prevent the user from clicking the browser’s “Back” button to return to the previous page (common for login redirects), use the replace option:

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

3. Passing State to the New Route

You can pass custom data to the destination route by including a state object in the options parameter.

navigate('/details', { state: { id: 101, admin: true } });

To access this state on the target page, use the useLocation hook:

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

function Details() {
  const location = useLocation();
  const { id, admin } = location.state || {};
  
  return <div>Item ID: {id}</div>;
}

To navigate through the browser history stack, pass an integer representing the step delta instead of a path string:

// Go back one page (equivalent to history.goBack())
navigate(-1);

// Go forward one page (equivalent to history.goForward())
navigate(1);

// Go back two pages
navigate(-2);