React Router Cheatsheet

Navigation and Links

Use this React Router reference while you build software engineering projects, review code, or refresh the syntax you reach for most.

useNavigate

For navigation that is not a user clicking a link: after a submit, on a timer, in a guard.

import { useNavigate } from "react-router";

function Form() {
  const navigate = useNavigate();

  async function onSubmit(data) {
    await save(data);
    navigate("/thanks");
    navigate("/thanks", { replace: true });
    navigate("/thanks", { state: { id: data.id } });
    navigate(-1);                    // back
    navigate(1);                     // forward
    navigate(-2);                    // back two entries
    navigate("/list", { preventScrollReset: true });
    navigate("/list", { viewTransition: true });
  }
}

Reach for <Link> first. useNavigate in an effect to "redirect if not logged in" is a common pattern that flashes the wrong UI first. Prefer <Navigate> during render, or a loader redirect() in data mode.

Programmatic History

import { useHref, useResolvedPath, useLinkClickHandler } from "react-router";

const href = useHref("/about");                  // includes the basename
const path = useResolvedPath("../sibling");      // what a relative `to` resolves to

// Build a custom link component that still behaves like a link
function CustomLink({ to, children, ...rest }) {
  const href = useHref(to);
  const handleClick = useLinkClickHandler(to);
  return <a href={href} onClick={handleClick} {...rest}>{children}</a>;
}