React by Patrik

useNavigate Hook in React

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

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

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

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

Button click

import { useNavigate } from 'react-router-dom';
...
const navigate = useNavigate();
...
<Button onClick={() => navigate('../user', { replace: true })}>Register</Button>

Reference

Comments

Leave a Comment

All fields are required. Your email address will not be published.