DEV Community

Cover image for ReactJS useNavigate() Hook
Karthick (k)
Karthick (k)

Posted on

ReactJS useNavigate() Hook

React Router v6 introduces the useNavigate() hook, making it easier and more flexible to navigate between different pages in your app. It replaces the older useHistory() hook.

With the useNavigate() hook, you can:

  • Go to a different page in your app.
  • Navigate based on actions like button clicks.
  • Send data or parameters when moving to another page.

How to Use useNavigate() for Navigation?

The useNavigate() hook in React Router v6 provides a programmatic way to navigate between routes in your application. Here's a step-by-step guide on how to use it:

Step 1: Install React Router

npm install react-router-dom@6
Enter fullscreen mode Exit fullscreen mode

Step 2: Import the useNavigate Hook

To begin, you need to import the useNavigate hook from react-router-dom.

import { useNavigate } from 'react-router-dom';
Enter fullscreen mode Exit fullscreen mode

Step 3: Call ** useNavigate()** Inside Your Component

Inside your functional component, call useNavigate() to access the navigate function. This function will allow you to programmatically change the route.

const navigate = useNavigate();

Step 4: Use navigate() to Change Routes

You can use the navigate function to navigate to a specific route. Here's the basic syntax:

navigate('/path');  // Navigates to '/path'

Enter fullscreen mode Exit fullscreen mode

When to Use useNavigate() vs. :

  1. useNavigate(): Best suited for programmatic navigation triggered by code, such as after form submissions, authentication events, or specific actions that aren't directly related to user interaction.

  2. <Link> or <NavLink>: Ideal for declarative navigation, where the route change is a part of the UI and driven by user interaction, like in menu items, buttons, or navigation bars.

Top comments (0)