All topics
Routingbeginner

Programmatic Navigation

Learn how to trigger navigation imperatively from event handlers or effects using React Router's useNavigate hook.

While <Link> handles declarative, user-clicked navigation, many situations require triggering navigation imperatively from code — after a form successfully submits, after a timed redirect, or in response to some business logic decision. React Router's useNavigate() hook returns a function you call with a path (or a delta like -1 for 'go back') to perform that navigation from inside an event handler or effect.

Programmatic navigation is like a receptionist who, instead of waiting for a visitor to walk up and ask for a room, proactively buzzes them through to a different room based on some internal decision (like confirming their appointment succeeded), while still using the exact same door system (browser history) as if the visitor had walked there themselves.

Key Concepts

1
navigate('/success') pushes a new entry onto the browser history stack by default, while navigate('/success', { replace: true }) replaces the current entry instead — important for cases like a post-login redirect, where you don't want the user's back button to return them to the login page they just left.
navigate('/success')navigate('/success', { replace: true })
2
navigate(-1) and navigate(1) move backward or forward through history exactly like the browser's back/forward buttons, useful for a generic 'Go back' button that doesn't need to know the specific previous URL. Passing a state object as part of the navigate options lets you carry non-URL data to the destination route, readable there via useLocation().state.
navigate(-1)navigate(1)stateuseLocation().state
3
Interviewers commonly ask when to use replace: true versus the default push behavior, expecting candidates to identify redirect-after-login and redirect-after-form-submission as classic cases where you don't want the 'previous' page re-accessible via the back button.
replace: true