React & Modern Frontend (445 Qs)•Part 10: Modern React 18, React 19 & Next.js Patterns (317 - 353)
How do you navigate programmatically in React Router?
In React Router v6+, programmatic navigation (redirecting from code rather than a user clicking a link) is done with the useNavigate hook, which replaces the old history.push()/this.props.history.push() approach from v4/v5 (see How do you programmatically navigate using React Router v4?).
jsx
import { useNavigate } from "react-router-dom";
function LoginForm() {
const navigate = useNavigate();
async function handleSubmit(e) {
e.preventDefault();
await login();
navigate("/dashboard"); // push a new entry (like clicking a link)
// navigate("/dashboard", { replace: true }); // replace current entry (no back button to login)
// navigate(-1); // go back, like history.back()
// navigate("/users/42", { state: { from: "login" } }); // pass state to the next route
}
return <form onSubmit={handleSubmit}>{/* ... */}</form>;
}
Key points:
navigate(to)pushes a new history entry;navigate(to, { replace: true })replaces the current one (useful after login/logout so the back button doesn't return to the old page).navigate(delta)with a number (e.g.,navigate(-1),navigate(1)) moves through history like the browser back/forward buttons.useNavigatecan only be called inside components rendered under a<Router>; it can't be used outside React (for that, some apps keep a module-level history object created withcreateBrowserRouter/historypackage instead).- Prefer declarative navigation (
<Link>/<NavLink>) for user-initiated clicks, and reserveuseNavigatefor navigation triggered by logic — form submissions, redirects after auth, timers, etc.