Programmatic Navigation
Learn to navigate programmatically using React Router hooks and functions. This is a foundational concept in component-based UI development that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world React experience. Take your time with each section and practice the examples
useNavigate Hook
The useNavigate hook returns a function that lets you navigate programmatically. This is useful for navigation after form submissions, API calls, or other events.. This is an essential concept that every React developer must understand thoroughly. In professional development environments, getting this right can mean the difference between code that works reliably and code that breaks in production. The following sections break this down into clear, digestible pieces with practical examples you can try immediately
Basic Navigation
import { useNavigate } from 'react-router-dom';
function LoginForm() {
const navigate = useNavigate();
const [credentials, setCredentials] = useState({
email: '',
password: ''
});
const handleSubmit = async (e) => {
e.preventDefault();
try {
// Simulate API call
const response = await loginUser(credentials);
if (response.success) {
// Navigate to dashboard after successful login
navigate('/dashboard');
}
} catch (error) {
}
};
return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={credentials.email}
onChange={(e) => setCredentials({
...credentials,
email: e.target.value
})}
placeholder="Email"
/>
<input
type="password"
value={credentials.password}
onChange={(e) => setCredentials({
...credentials,
password: e.target.value
})}
placeholder="Password"
/>
<button type="submit">Login</button>
</form>
);
}Advanced Navigation
// Navigation with state
function ProductCard({ product }) {
const navigate = useNavigate();
const handleViewDetails = () => {
navigate(`/products/${product.id}`, {
state: { product }
});
};
const handleEdit = () => {
navigate(`/products/${product.id}/edit`, {
state: { product },
replace: true
});
};
return (
<div>
<h3>{product.name}</h3>
<p>{product.description}</p>
<button onClick={handleViewDetails}>View Details</button>
<button onClick={handleEdit}>Edit</button>
</div>
);
}
// Receiving state in target component
function ProductDetail() {
const location = useLocation();
const product = location.state?.product;
return (
<div>
<h1>{product?.name}</h1>
<p>{product?.description}</p>
</div>
);
}
// Navigation with query parameters
function SearchResults() {
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const handleSort = (sortBy) => {
const currentParams = Object.fromEntries(searchParams);
navigate(`?${new URLSearchParams({
...currentParams,
sort: sortBy
})}`);
};
return (
<div>
<button onClick={() => handleSort('name')}>Sort by Name</button>
<button onClick={() => handleSort('price')}>Sort by Price</button>
</div>
);
}