Routing with React Router
React Router useNavigate Hook
useNavigate returns a function that changes the route programmatically. Use it when navigation is the result of logic rather than a click on a link — after a successful login, after a form submit, or on a timeout.
What is Router useNavigate Hook in React?
useNavigate returns a function that changes the route programmatically. Use it when navigation is the result of logic rather than a click on a link — after a successful login, after a form submit, or on a timeout.
Router useNavigate Hook example
import { useNavigate } from 'react-router-dom';
function Login() {
const navigate = useNavigate();
async function handleSubmit(e) {
e.preventDefault();
const ok = await login(email, password);
if (ok) navigate('/dashboard', { replace: true });
}
}How this works
replace: true swaps the login page out of the history stack, so pressing back from the dashboard does not return the user to a login form they have already completed.
Key points to remember
- navigate(-1) goes back, navigate(1) goes forward.
- Pass state with navigate(path, { state }) and read it with useLocation.
- Call it inside handlers or effects — never during render.
Common mistakes with Router useNavigate Hook
- Calling navigate directly in the component body, which triggers an update during render.
- Pushing instead of replacing after login, leaving a back-button trap.
React Router useNavigate Hook— Interview Questions & FAQs
How do I redirect programmatically in React Router v6?+
Call the function returned by useNavigate: navigate("/path"). The old useHistory hook and Redirect component from v5 no longer exist.
