Topic 39 of 54
useNavigate
Overview
Sometimes you need to navigate the user to a new page without them explicitly clicking a `<Link>`. For example, redirecting them to the Dashboard *after* they successfully submit a login form, or sending them back to the previous page when they click a 'Cancel' button. This is called 'Programmatic Navigation', and it's handled by the `useNavigate` hook.
Syntax
`useNavigate` gives you a function that you can call inside event handlers or `useEffect` blocks to force a route change.
Using useNavigate
jsx
import { useNavigate } from 'react-router-dom';
import { useState } from 'react';
function LoginForm() {
const navigate = useNavigate(); // Get the navigate function
const [isSubmitting, setIsSubmitting] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
setIsSubmitting(true);
// Simulate an API login call
const success = await api.login();
if (success) {
// Programmatically route the user to the dashboard
navigate('/dashboard');
} else {
alert("Login failed");
setIsSubmitting(false);
}
};
return (
<form onSubmit={handleSubmit}>
<button type="submit" disabled={isSubmitting}>Log In</button>
</form>
);
}The `{ replace: true }` option is critical for authentication flows. It overwrites the current history stack entry instead of adding a new one.
Replace and Go Back
jsx
// Going back one page in history (like hitting the browser Back button)
navigate(-1);
// Going forward one page
navigate(1);
// Replacing the current history entry
// Use this for Login pages so the user can't hit 'Back' and return to the login screen!
navigate('/dashboard', { replace: true });Common Pitfalls
- Calling `navigate()` directly inside the render body (not inside a `useEffect` or event handler). This will trigger an infinite rendering loop and crash React.
Interview Tips
- In older versions of React Router (v5), this was done using `useHistory()` and `history.push()`. If you mention that `useNavigate` replaced `useHistory` in v6, you sound very experienced.
Real-World Example
A 404 Not Found page that automatically redirects the user home after 5 seconds.
example
jsx
function NotFound() {
const navigate = useNavigate();
useEffect(() => {
const timer = setTimeout(() => {
// Automatically navigate to home, replacing the 404 in history
navigate('/', { replace: true });
}, 5000);
return () => clearTimeout(timer);
}, [navigate]);
return <h1>404: Page not found. Redirecting in 5s...</h1>;
}