useNavigateThe useNavigate hook returns a function that lets you navigate programmatically in the browser in response to user interactions or effects.
import { useNavigate } from "@remix-run/react";
function SomeComponent() {
const navigate = useNavigate();
return (
<button
onClick={() => {
navigate(-1);
}}
/>
);
}
It's often better to use redirect in actions and loaders than this hook, but it still has use cases.
to: stringThe most basic usage takes an href string:
navigate("/some/path");
Paths can be relative:
navigate("..");
navigate("../other/path");
useResolvedPath docs for a note on the behavior of the future.v3_relativeSplatPath future flag for relative useNavigate() behavior within splat routes
to: Partial<Path>You can also pass a Partial<Path> value:
navigate({
pathname: "/some/path",
search: "?query=string",
hash: "#hash",
});
to: NumberPassing a number will tell the browser to go back or forward in the history stack:
navigate(-1); // go back
navigate(1); // go forward
navigate(-2); // go back two
Note that this may send you out of your application since the history stack of the browser isn't scoped to just your application.
optionsThe second argument is an options object:
navigate(".", {
replace: true,
relative: "path",
state: { some: "state" },
});
"route" | "path" — defines the relative path behavior for the link
"route" will use the route hierarchy so ".." will remove all URL segments of the current route pattern while "path" will use the URL path so ".." will remove one URL segment<ScrollRestoration>, prevent the scroll position from being reset to the top of the window when navigatingReactDOM.flushSync call instead of the default React.startTransitiondocument.startViewTransition()
useViewTransitionState()