Building a Multi-Page SPA with React RouterEntry 7 of 20
Programmatic Navigation with useNavigate
useNavigate() returns a navigate function for changing routes from code, e.g. after a timer or a button click that does more than link.
Notes
- Don't confuse
useNavigate(navigate from code) withuseNavigation(read pending state, Entry 12). navigate('/products')pushes a history entry;navigate(-1)goes back;navigate('/login', { replace: true })replaces the current entry.- Prefer
<Link>for plain navigation. Inside actions and loaders, useredirect()instead (Entry 15).
What / Why / When
- What
Imperative navigation.
- Why
Navigate after logic runs, not just on a link click.
- When
After a non-form operation, timeouts, conditional flows.
Code compare
import { useNavigate } from "react-router";export default function HomePage() { const navigate = useNavigate(); function handleNavigate() { navigate("/products"); } return <button onClick={handleNavigate}>Navigate</button>;}@Component({ selector: "app-home", template: `<button (click)="handleNavigate()">Navigate</button>`,})export class HomeComponent { private router = inject(Router); handleNavigate() { this.router.navigate(["/products"]); }}Quick reference
| React | Angular |
|---|---|
navigate('/products') | router.navigate(['/products']) |
navigate(-1) | inject(Location).back() |
navigate(path, { replace: true }) | router.navigate([...], { replaceUrl: true }) |