useNavigate

useNavigate

It's usually better to use redirect in loaders and actions than this hook

The useNavigate hook returns a function that lets you navigate programmatically, for example in an effect:

import { useNavigate } from "react-router-dom";

function useLogoutTimer() {
  const userIsInactive = useFakeInactiveUser();

  useEffect(() => {
    if (userIsInactive) {
      fake.logout();
      navigate("/session-timed-out");
    }
  }, [userIsInactive]);
}

Type Declaration

declare function useNavigate(): NavigateFunction;

interface NavigateFunction {
  (
    to: To,
    options?: {
      replace?: boolean;
      state?: any;
      relative?: RelativeRoutingType;
    }
  ): void;
  (delta: number): void;
}

The navigate function has two signatures:

  • Either pass a To value (same type as <Link to>) with an optional second { replace, state } arg or
  • Pass the delta you want to go in the history stack. For example, navigate(-1) is equivalent to hitting the back button.
Docs and examples CC 4.0