ReactEasy

What is useNavigate?

useNavigate() is a React Router hook that returns a navigate function for changing routes from code: navigate("/dashboard"), navigate(-1) to go back, or navigate("/login", { replace: true, state: { from } }). Use it after logic completes, such as a successful save; use <Link> for ordinary links and redirect() inside loaders and actions.

Signature

navigate(to, options?)

  • to: a path string (absolute or relative to the current route), an object { pathname, search, hash }, or a number for history delta (-1, 1).
  • Options: replace (replace the current history entry), state (data available as useLocation().state), relative: "path" (resolve relative to the URL rather than the route hierarchy), preventScrollReset, viewTransition (wrap in a View Transition).

Rules

  • Call it in event handlers or effects, never during render. To redirect while rendering, return <Navigate to=... />.
  • Navigation is wrapped in a React transition; useNavigation() exposes pending state.

When to prefer other tools

  • Links: <Link>/<NavLink> for anything clickable that goes somewhere (supports middle-click, new tab, accessibility).
  • Data mode/framework mode: throw redirect("/login") in loaders, actions or middleware avoids rendering the wrong page first.
  • Forms: <Form> plus an action that returns redirect().

Next.js equivalent

useRouter() from next/navigation (router.push, router.replace, router.back), or redirect() on the server.

Code example

tsx
1import { useLocation, useNavigate } from "react-router";
2
3export function LoginForm() {
4 const navigate = useNavigate();
5 const location = useLocation();
6 const from = (location.state as { from?: string } | null)?.from ?? "/dashboard";
7
8 async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
9 e.preventDefault();
10 const res = await fetch("/api/login", { method: "POST", body: new FormData(e.currentTarget) });
11 if (res.ok) {
12 // replace: Back should not return to the login form
13 navigate(from, { replace: true });
14 }
15 }
16
17 return (
18 <form onSubmit={onSubmit}>
19 <input name="email" type="email" required />
20 <input name="password" type="password" required />
21 <button>Sign in</button>
22 <button type="button" onClick={() => navigate(-1)}>Cancel</button>
23 </form>
24 );
25}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app