Programmatic Navigation
Learn to navigate programmatically using React Router hooks and functions
50 min•By Priygop Team•Last updated: Feb 2026
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.
Basic Navigation
Example
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
Example
// 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>
);
}Try It Yourself — React Router
Try It Yourself — React RouterHTML
HTML Editor
✓ ValidTab = 2 spaces
HTML|53 lines|2171 chars|✓ Valid syntax
UTF-8