Programmatic Navigation with useNavigate
In this lesson, we will learn how to navigate between routes using JavaScript logic, button clicks, form submissions, and other application events with the useNavigate hook.
1. What Is Programmatic Navigation?
Programmatic navigation means changing the current route through application logic instead of asking the user to click a normal navigation link.
For example, after a user submits a form successfully, the application can automatically navigate to a dashboard. Similarly, after adding a course to a shopping cart, the application may navigate to the cart page.
Remember: Use programmatic navigation when navigation should happen because of an event or application condition.
2. What Is the useNavigate Hook?
useNavigate is a React Router hook that returns a function for navigating to another route. You can call this function inside an event handler or another suitable part of your component logic.
Import useNavigate
import { useNavigate } from 'react-router-dom';
Basic Syntax
const navigate = useNavigate();
navigate('/courses');
Here, useNavigate returns the navigate function. Calling navigate with /courses changes the current route to that destination.
Important: Call useNavigate at the top level of a React component or custom hook, not inside an event handler, loop, or conditional statement. Call the returned navigate function inside the event handler.
3. Navigate When a Button Is Clicked
One common use of useNavigate is to navigate to another page when the user clicks a button.
Example
import { useNavigate } from 'react-router-dom';
function Home() {
const navigate = useNavigate();
function openCourses() {
navigate('/courses');
}
return (
<div>
<h2>Home Page</h2>
<button onClick={openCourses}>
View Courses
</button>
</div>
);
}
export default Home;
Explanation
- Import useNavigate from React Router.
- Call useNavigate inside the Home component.
- Store the returned function in navigate.
- Define the openCourses event handler.
- Call navigate('/courses') when the button is clicked.
Expected Behavior
Home Page
[ View Courses ]
Clicking View Courses navigates to /courses, where the matching Courses route should render.
4. Navigate After Form Submission
Suppose a student enters their name into a registration form. After the form is submitted successfully, we can navigate to a confirmation page.
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
function Registration() {
const [studentName, setStudentName] = useState('');
const navigate = useNavigate();
function handleSubmit(event) {
event.preventDefault();
if (studentName.trim() !== '') {
navigate('/confirmation');
}
}
return (
<form onSubmit={handleSubmit}>
<h2>Student Registration</h2>
<input
type="text"
value={studentName}
onChange={(event) =>
setStudentName(event.target.value)
}
placeholder="Enter student name"
/>
<button type="submit">
Register
</button>
</form>
);
}
export default Registration;
Explanation
- useState stores the value entered by the student.
- onChange updates studentName as the user types.
- onSubmit calls handleSubmit when the form is submitted.
- event.preventDefault() prevents the browser's default form submission.
- If the name is not empty, navigate moves to /confirmation.
Note: This is a basic client-side example. A real registration form should validate and save the information through the appropriate backend before navigating to the confirmation page.
5. Navigate After a Successful Login
In an application, a successful login may redirect the user to a dashboard. Navigation should happen only after the application has confirmed that authentication succeeded.
import { useNavigate } from 'react-router-dom';
function Login() {
const navigate = useNavigate();
async function handleLogin() {
// Replace this with real authentication.
const loginSuccessful = true;
if (loginSuccessful) {
navigate('/dashboard', { replace: true });
}
}
return (
<div>
<h2>Login Page</h2>
<button onClick={handleLogin}>
Login
</button>
</div>
);
}
export default Login;
Explanation
In this simplified example, loginSuccessful represents the result of an authentication process. In a real application, replace it with the actual result returned by your login service or API.
The option replace: true replaces the current history entry instead of adding another entry. This can prevent the Login page from remaining as the immediately previous history entry.
Never treat a hardcoded success value as real authentication. Protect sensitive routes with proper authentication and authorization checks.
6. Navigate Backward and Forward
The navigate function can also move through browser history using a numeric argument.
Go Back
navigate(-1);
This navigates to the previous history entry when one exists.
Go Forward
navigate(1);
This navigates to the next history entry when one exists.
Complete Example
import { useNavigate } from 'react-router-dom';
function CourseDetails() {
const navigate = useNavigate();
return (
<div>
<h2>Course Details</h2>
<button onClick={() => navigate(-1)}>
Go Back
</button>
<button onClick={() => navigate(1)}>
Go Forward
</button>
</div>
);
}
export default CourseDetails;
The previous or next history entry may not exist. For example, navigate(-1) may leave the application if the user arrived from another website.
7. Passing State During Navigation
Sometimes a component needs to pass temporary information to the destination route. The navigate function supports a state option for this purpose.
Send Data from One Component
import { useNavigate } from 'react-router-dom';
function Courses() {
const navigate = useNavigate();
function openDetails() {
navigate('/course-details', {
state: {
courseName: 'React Development'
}
});
}
return (
<button onClick={openDetails}>
View Course Details
</button>
);
}
export default Courses;
Read State in the Destination Component
import { useLocation } from 'react-router-dom';
function CourseDetails() {
const location = useLocation();
const courseName =
location.state?.courseName ?? 'Course Details';
return (
<h2>{courseName}</h2>
);
}
export default CourseDetails;
The destination component reads the navigation state through useLocation. Optional chaining and the fallback value prevent an error if the state is missing.
Navigation state is useful for temporary UI information. Do not rely on it as the only source for essential data; users may open a URL directly or refresh the page.
8. Difference Between Link and useNavigate
| Feature | Link | useNavigate |
|---|---|---|
| Purpose | Provides a navigation link for the user. | Changes routes through application logic. |
| Typical use | Navigation menus and page links. | Form submission, event handlers, and redirects. |
| How it is used | Rendered as a component. | Called through a function returned by the hook. |
| Example | Link to /courses | navigate('/courses') |
Use Link when users should click a navigation link. Use useNavigate when a navigation decision should happen in response to application logic.
9. Common Mistakes
Mistake 1: Calling the hook inside an event handler
// Incorrect
function Home() {
function openCourses() {
const navigate = useNavigate();
navigate('/courses');
}
return <button onClick={openCourses}>Courses</button>;
}
Call useNavigate at the top level of the component instead.
// Correct
function Home() {
const navigate = useNavigate();
function openCourses() {
navigate('/courses');
}
return <button onClick={openCourses}>Courses</button>;
}
Mistake 2: Using an undefined destination route
Verify that the destination path is configured in your Routes component.
Mistake 3: Navigating before an operation succeeds
When submitting a form or authenticating a user, wait for the required operation to succeed before redirecting.
Mistake 4: Forgetting the router provider
Components using useNavigate must be rendered inside the appropriate router provider.
Practice Tasks
- Create a button that navigates from Home to Courses.
- Create a form that navigates to a confirmation route after valid input.
- Build a simplified login example that redirects to Dashboard after success.
- Create Go Back and Go Forward buttons using navigate(-1) and navigate(1).
- Pass a course name through navigation state.
- Read the navigation state using useLocation.
- Explain the difference between Link and useNavigate.
- Correct an example that calls useNavigate inside an event handler.
Summary
The useNavigate hook returns a function for programmatic navigation in React Router. It is useful when a route change should happen after a button click, successful form submission, or completed application action. It also supports history navigation with numeric arguments, replacement of the current history entry, and passing temporary navigation state. Call useNavigate at the top level of your component and use the returned function inside event handlers. In the next lesson, we will learn URL parameters and the useParams hook.