Programmatic navigation with useNavigate
useNavigate changes the location from code, for moments when the app moves the user on its own, like after a login form or when a session times out.
How it works
- Get the navigate function.
LoginPageandWelcomeboth calluseNavigate()and keep the returnednavigatefunction. [1] - Navigate after a form submission. The form's submit handler calls
navigate(`/welcome/${name}`), and the welcome page reads the name withuseParams. [1] - Log out after a timer.
Welcomecounts down from 10 in auseEffectand callsnavigate('/')when it reaches zero. The normal menu links still useLink. [1]
Run and edit it
It runs in your browser, in a sandboxed frame that cannot see this site; the packages load from esm.sh only after you press Run.
Checked Oct 12, 2026: it starts without errors in Chromium with react-router-dom 7.18.4, react 19.3.0, react-dom 19.3.0. Needs WebGL.
More React Router examples
Basic routing in React Router Nested routes with Outlet in React Router URL params with useParams in React Router Active links with NavLink in React Router
Sources
Explanations written by AgentGid from the official docs; the numbers in brackets point here. The code marked "written by AgentGid" is ours and free to copy.