useNavigate Hook
The useNavigate hook is a programmatic way to navigate between routes in React Router. It returns a function that can be used to navigate to different routes. It allows us to create more complex navigation logic that might depend on certain conditions or events.
Key Features
- Programmatic Navigation: Allows navigation based on events, conditions, or actions beyond simple link clicks.
- Flexible Navigation Logic: Can navigate to routes dynamically based on application state or logic.
- Supports Navigation Options: Allows passing state or options to the new route.
Example: In this example the useNavigate hook is used to get the navigate function. The handleButtonClick function uses navigate(‘/dashboard’) to programmatically navigate to the /dashboard route when the button is clicked.
// App.js
import React from 'react';
import { Route, Routes } from 'react-router-dom';
import { BrowserRouter } from 'react-router-dom'
import Dashboard from './components/Dashboard';
import LoginPage from './components/LoginPage';
const App = () => {
return (
<BrowserRouter>
<Routes>
<Route path="dashboard" element={<Dashboard/>} />
<Route path="/" element={<LoginPage />} />
</Routes>
</BrowserRouter>
);
};
export default App;
// LoginPage.js
import { useNavigate } from 'react-router-dom';
function LoginPage() {
const navigate = useNavigate();
const handleButtonClick = () => {
navigate('/dashboard');
};
return (
<>
<h3>Welcome to w3wiki</h3>
<button onClick={handleButtonClick}>
Go to Dashboard
</button>
</>
);
}
export default LoginPage;
// Dashboard.js
import React from 'react';
import { useNavigate } from 'react-router-dom';
const Dashboard = () => {
return (
<div>
<h2>Hello Geek welcome to Dashboard</h2>
</div>
);
};
export default Dashboard;
Output:
Difference between NavLink and useNavigate hook
NavLink and useNavigate are two important utilities provided by the React Router library to manage navigation in a React application. While both serve the purpose of navigation, they are used in different contexts and offer distinct functionalities. In this article, we will explore the difference between them.