Hello! Welcome to the next lesson in our module on client-side routing.
In our previous lessons, we focused on declarative navigation. You learned how to use <Link> to let users move between pages and useParams to read dynamic values from the URL. This is fantastic for user-initiated navigation, but what happens when the application needs to take control? For example, redirecting a user after they log in, or sending them to an error page if an API call fails.
This lesson addresses that exact need by focusing on the learning outcome: Perform programmatic navigation using the useNavigate hook. We'll explore how to trigger navigation from within your component logic, giving you complete control over the user's journey through your application.
From Declarative to Programmatic Navigation
While <Link> is the right tool for standard navigation (like in a navbar or a list of items), there are many scenarios where you need to change routes based on an event or a state change within your component's logic. This is called programmatic, or imperative, navigation.
In React Router v6, the primary tool for this is the useNavigate hook.
To start, let's watch a short video that introduces the hook and contrasts it with the older useHistory hook from React Router v5.
React Router 6 Tutorial #3 - Redirects & useNavigate
Watch this clip from 'React Router 6 Tutorial #3 - Redirects & useNavigate' by Net Ninja. It provides a clear, concise demonstration of how to import useNavigate and use it within a button's click handler.
Watch from 05:52 to 07:44. Notice how the useNavigate hook is called at the top level of the component, and the returned navigate function is then used inside an event handler.
As you saw, the basic pattern is simple:
- Import
useNavigatefromreact-router-dom. - Call the hook in your component to get the
navigatefunction:const navigate = useNavigate();. - Call
navigate()with a path whenever you need to redirect:navigate('/some-path');.
When to Use useNavigate
The useNavigate hook is essential for dynamic, logic-driven routing. Here are some of the most common scenarios where you'll need it:
- After form submissions: Redirecting a user to a "success" page or their dashboard after they log in or submit data.
- Conditional navigation: Redirecting a user based on their authentication status or role (e.g., sending an unauthenticated user to the login page).
- Post-API call actions: Navigating to a product page after creating it, or to an error page if a data fetch fails.
- Time-based events: Automatically logging a user out and redirecting them to a "session timed out" page after a period of inactivity.
The navigate Function in Detail
The navigate function is more powerful than just taking a simple path. Let's dive into its capabilities by consulting the official React Router documentation.
Please read the introduction to the useNavigate hook in the official React Router documentation. This will show you the hook's TypeScript signature and provide another example of its use.
Read the first section of the page, down to just before the 'options.replace' heading. Pay attention to the NavigateFunction interface, which shows the two ways you can call navigate.
The documentation reveals two primary ways to call navigate:
navigate(to: To, options?: NavigateOptions): Navigate to a specific path, with optional settings.navigate(delta: number): Move forward or backward in the browser's history stack.
Let's explore these in a practical context.
Example: Creating a New Post
Imagine you have a form to create a new blog post. After the user clicks "Submit", you want to send them to the page for the newly created post.
// src/pages/CreatePostPage.tsx
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
export function CreatePostPage() {
const navigate = useNavigate();
const [title, setTitle] = useState('');
const handleSubmit = (event: React.FormEvent) => {
event.preventDefault();
// In a real app, you would send the data to an API
// and get back the new post's ID.
const newPostId = Math.random().toString(36).substring(2, 9);
console.log(`Creating post with title: ${title} and ID: ${newPostId}`);
// Navigate to the new post's page
navigate(`/posts/${newPostId}`);
};
return (
<div>
<h1>Create a New Post</h1>
<form onSubmit={handleSubmit}>
<label>
Title:
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
</label>
<button type="submit" disabled={!title}>Submit</button>
</form>
</div>
);
}
In this example, navigate(/posts/${newPostId}) programmatically changes the URL, and React Router will render the component associated with that dynamic route (which you learned to build in the last lesson!).
Advanced Navigation Options
The navigate function's second argument, options, gives you finer control over the navigation behavior.
1. Replacing History (replace: true)
By default, navigate pushes a new entry onto the browser's history stack. This means the user can click the "back" button to return to the previous page. For a login form, this is undesirable; you don't want a logged-in user to be able to go back to the login screen.
Using { replace: true } replaces the current history entry instead of adding a new one.

2. Navigating the History Stack
You can also navigate relative to the current position in the history stack by passing a number.
navigate(-1): Go back one page (equivalent tohistory.back()).navigate(-2): Go back two pages.navigate(1): Go forward one page.
3. Passing State
Sometimes you need to pass temporary data between routes that isn't part of the URL. A classic example is redirecting a user to a login page and, after they log in, sending them back to the page they were originally trying to access.
You can achieve this with the state option. The data passed in state is then accessible on the destination route using the useLocation hook.
// In a component that requires authentication
import { useLocation, useNavigate } from 'react-router-dom';
function ProtectedPage() {
const navigate = useNavigate();
const location = useLocation();
const isAuthenticated = false; // Assume we get this from context or a store
if (!isAuthenticated) {
// Redirect to login, but pass the current path in state
// so we can come back here after a successful login.
navigate('/login', { state: { from: location.pathname }, replace: true });
}
return <div>Secret Content</div>;
}
// In your LoginPage component
import { useLocation, useNavigate } from 'react-router-dom';
function LoginPage() {
const navigate = useNavigate();
const location = useLocation();
// Type the state to be safe. It might not exist on direct navigation.
const from = (location.state as { from?: string })?.from || '/dashboard';
const handleLogin = () => {
// ... authentication logic ...
// On success, navigate to the 'from' path
navigate(from, { replace: true });
};
// ...
}
The following video demonstrates these advanced options clearly.
Learn React Router v6 In 45 Minutes
This clip from 'Learn React Router v6 In 45 Minutes' by Web Dev Simplified provides excellent demonstrations of programmatic navigation, including using replace, navigating back with navigate(-1), and simulating a redirect after a delay.
Watch from 00:36:34 to 00:39:09. The video shows a common pattern of redirecting inside a useEffect hook, which is useful for time-based actions.
Test your understanding!
You are implementing a "Logout" button. When clicked, it should clear the user's session data and redirect them to the home page (/).
- Which hook would you use to perform the redirection?
- How would you call the navigation function?
- Should you use the
{ replace: true }option? Why or why not?
Show answer
- You would use the
useNavigatehook. - Inside the button's
onClickhandler, you would callnavigate('/', { replace: true });. - Yes, you should absolutely use
{ replace: true }. After logging out, the user should not be able to use the browser's back button to return to the protected, authenticated parts of the application. Replacing the history entry prevents this.
Production-Ready Patterns
For a comprehensive look at how useNavigate is used in practice, including how to abstract navigation logic into custom hooks (a pattern you'll appreciate given your software engineering background), the following article is an excellent resource.
Redirect in React Router V6 with useNavigate hook
Please read this article from Refine.dev, 'Redirect in React Router V6 with useNavigate hook'. It synthesizes everything we've discussed and provides further real-world examples and patterns.
Read the sections 'How to use the useNavigate hook', 'When to Use the useNavigate Hook', and 'Some common examples...'. Pay special attention to the examples of creating custom hooks like useAuthNavigate at the end. This demonstrates how to create clean, reusable navigation logic in a larger application.
Conclusion
You have now learned how to perform programmatic navigation, a critical skill for building dynamic and responsive React applications. You are no longer limited to user-initiated navigation via <Link> and can now direct users based on application logic, user actions, and API responses.
Key Takeaways:
- The
useNavigatehook returns anavigatefunction for programmatic routing. - It's used for logic-driven navigation, such as after form submissions or authentication checks.
- The
navigatefunction can take a path string or a number to move through the browser history. - The
{ replace: true }option is crucial for authentication flows to prevent users from navigating back to protected pages after logging out. - The
{ state: { ... } }option allows you to pass temporary data between routes, which can be accessed with theuseLocationhook.
Preview of the Next Lesson:
We've covered how to define routes, link between them, and navigate programmatically. Now, we'll turn our attention to layout. In the next lesson, we will learn how to create nested UI layouts using nested routes and the <Outlet> component. This will allow us to build complex UIs with shared components like sidebars and headers that persist across related routes.