Redirects and No Match

Navigate, Redirects and No Match Routes

<Navigate> is useNavigate as an element: rendering it performs the navigation in an effect, which is what you need when the decision belongs to the render tree rather than to an event handler. Two patterns cover most redirects. A no-match route is a <Route path="*">: it matches every URL but, because matching is scored rather than ordered, always loses to a more specific route, so it fires only when nothing else matched. An old URL gets a <Route> whose element is a <Navigate>, keeping stale links alive without a server rule.

A 404 route and a moved URLXML
<Routes>
  {/* ...the route table of Section 2.16.6, plus these two rows */}
  <Route path="/old-docs/*" element={<Navigate to="/docs" replace />} />
  <Route path="*" element={<NotFound />} />
</Routes>
function NotFound() {
  const { pathname } = useLocation();
  return <><h3>No page at <code>{pathname}</code></h3><Link to="/">Home</Link></>;
}

replace is nearly always right on a redirect. Without it the URL you are bouncing away from stays in history, so Back lands on it, the redirect fires again, and the user is trapped. <Navigate> also takes state and relative; the from prop of React Router 5 139,386 is gone.

For a redirect that depends on data rather than on the URL, render nothing and navigate — a component returning <Navigate to="/login" replace /> when a check fails is the whole guard in the next subsection.