How do you navigate programmatically in React Router?
Assesses fundamental understanding of React conventions, runtime behavior, and memory/performance considerations.
Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.
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?](#how-do-you-programmatically-navigate-using-react-router-v4)).
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.
Candidate Response Strategy & Interview Tips
- Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
- Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
- Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
- Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.