![]() |
VOOZH | about |
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:
Step 1: To start with, create a React application using the following command:
npm create vite@latest demoStep 2: Move to the project directory.
cd demoStep 3: Install the latest version of react-router-dom in the React application by the following.
npm install react-router-dom@6Project Structure:
👁 ImageThe updated dependencies in package.json file.
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.19.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
Output
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:
npm install react-router-dom@6To begin, you need to import the useNavigate hook from react-router-dom.
import { useNavigate } from 'react-router-dom';Inside your functional component, call useNavigate() to access the navigate function. This function will allow you to programmatically change the route.
const navigate = useNavigate();You can use the navigate function to navigate to a specific route. Here's the basic syntax:
navigate('/path'); // Navigates to '/path'replace for One-Time RedirectionYou can also use the { replace: true } option to replace the current history entry. This is useful for cases like login redirects, where you don’t want users to be able to use the back button to return to the previous page.
navigate('/path', { replace: true });To navigate back in the browser’s history, use a negative number (e.g., -1), and to move forward, use a positive number (e.g., 1):
navigate(-1); // Goes back one step in historynavigate(1); // Goes forward one step in historyIn this example:
BrowserRouter, defining routes for / (Home) and /about (About)./about page using useNavigate().useNavigate(-1)./about, and "Go Back Home" takes you back to /.Home and About.