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
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';
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'
When to Use useNavigate() vs. :
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.
<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)