Lesson 5 of 10
Programmatic Navigation
Navigation doesn't always happen on a link click. After form submission, login, or basket operations, you need to navigate programmatically. useNavigate provides imperative navigation with support for replace (no history entry), state (passing data between routes), and relative navigation.
useNavigate - Programmatic Navigation
import { useNavigate, useLocation } from 'react-router-dom';
function LoginForm() {
const navigate = useNavigate();
const location = useLocation();
// Where the user was trying to go before being redirected to login
const from = (location.state as { from?: Location })?.from?.pathname ?? '/dashboard';
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
const formData = new FormData(e.target as HTMLFormElement);
try {
await loginUser({ email: formData.get('email'), password: formData.get('password') });
// ✅ replace: true - don't add /login to history (so back button skips it)
navigate(from, { replace: true });
} catch (err) {
setError('Invalid credentials');
}
}
return <form onSubmit={handleSubmit}>...</form>;
}
// Navigating with state - pass data without putting it in the URL
function ProductCard({ product }: { product: Product }) {
const navigate = useNavigate();
function handleQuickView() {
navigate(`/products/${product.id}`, {
state: { fromList: true, scrollPosition: window.scrollY }
});
}
}
// Consuming navigation state
function ProductDetail() {
const location = useLocation();
const state = location.state as { fromList?: boolean; scrollPosition?: number };
// Show breadcrumb only when navigated from list
return (
<>
{state?.fromList && <Breadcrumb label="← Back to products" />}
...
</>
);
}
// Relative navigation
function UserSettings() {
const navigate = useNavigate();
return <button onClick={() => navigate('security')}>Security Settings</button>;
// Navigates to /users/settings/security (relative to current route)
}
// navigate(-1) is the browser back button equivalent
<button onClick={() => navigate(-1)}>Go Back</button>Tip
Tip
Practice Programmatic Navigation in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and flow for Programmatic Navigation
Practice Task
Note
Practice Task - (1) Write a working example of Programmatic Navigation from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Programmatic Navigation is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.
Finished this lesson?