Programmatic Navigation with `useNavigate`: How to Navigate from Your Code #95
📖 Introduction
Following our exploration of dynamic routing, this article focuses on another essential feature of React Router: programmatic navigation. We will learn how to use the useNavigate
hook to navigate between routes from within our component's logic.
📚 Prerequisites
Before we begin, please ensure you have a solid grasp of the following concepts:
- All concepts from the previous articles in this series.
- Basic React hooks.
🎯 Article Outline: What You'll Master
In this article, you will learn:
- ✅ The
useNavigate
Hook: What it is and how it works. - ✅ Core Implementation: How to use the
useNavigate
hook to navigate to a different route. - ✅ Practical Application: Building a login form that redirects the user to a dashboard after a successful login.
🧠 Section 1: The Core Concepts of useNavigate
While the <Link>
and <NavLink>
components are great for user-initiated navigation, there are many times when you'll need to navigate programmatically. For example, after a user submits a form, you might want to redirect them to a different page.
The useNavigate
hook is the tool for this job. It returns a function that you can call to navigate to a different route.
💻 Section 2: Deep Dive - Implementation and Walkthrough
Let's see how to use the useNavigate
hook.
2.1 - The useNavigate
Hook in Action
// MyComponent.js
import React from 'react';
import { useNavigate } from 'react-router-dom';
function MyComponent() {
const navigate = useNavigate();
const handleClick = () => {
navigate('/about');
};
return (
<button onClick={handleClick}>
Go to About Page
</button>
);
}
export default MyComponent;
Step-by-Step Code Breakdown:
import { useNavigate } from 'react-router-dom';
: We import theuseNavigate
hook from React Router.const navigate = useNavigate();
: We call theuseNavigate
hook to get thenavigate
function.navigate('/about');
: We call thenavigate
function with the path we want to navigate to.
🛠️ Section 3: Project-Based Example: A Login Form
Let's build a simple login form that redirects the user to a dashboard after a successful login.
3.1 - The LoginForm
Component
// LoginForm.js
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
function LoginForm() {
const [username, setUsername] = useState('');
const navigate = useNavigate();
const handleSubmit = (event) => {
event.preventDefault();
// In a real application, you would have some authentication logic here
if (username) {
navigate('/dashboard');
}
};
return (
<form onSubmit={handleSubmit}>
<label>
Username:
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</label>
<button type="submit">Login</button>
</form>
);
}
export default LoginForm;
3.2 - The Dashboard
Component
// Dashboard.js
import React from 'react';
function Dashboard() {
return <h1>Welcome to your Dashboard!</h1>;
}
export default Dashboard;
3.3 - The App.js
File
// App.js
import React from 'react';
import { Routes, Route } from 'react-router-dom';
import LoginForm from './LoginForm';
import Dashboard from './Dashboard';
function App() {
return (
<Routes>
<Route path="/" element={<LoginForm />} />
<Route path="/dashboard" element={<Dashboard />} />
</Routes>
);
}
export default App;
Now, when you enter a username and click the "Login" button, you will be redirected to the dashboard page.
💡 Conclusion & Key Takeaways
In this article, we've learned how to use the useNavigate
hook to navigate programmatically in our React applications. This is an essential tool for building dynamic and interactive user experiences.
Let's summarize the key takeaways:
- The
useNavigate
hook returns a function that you can call to navigate to a different route. - It's useful for redirecting users after events like form submissions.
Challenge Yourself: To solidify your understanding, try to add a "Logout" button to the dashboard that redirects the user back to the login page.
➡️ Next Steps
You now have a solid understanding of how to use the useNavigate
hook. In the next article, "Nested Routes and Layouts", we will learn how to create complex layouts with nested routes.
Thank you for your dedication. Stay curious, and happy coding!
glossary
useNavigate
: A hook provided by React Router that allows you to navigate programmatically.- Programmatic Navigation: Navigating to a different route from within your code, rather than through a user-initiated action like clicking a link.