Home > Blockchain >  How to get useNavigate to push only if the new URI is different from the current?
How to get useNavigate to push only if the new URI is different from the current?

Time:08-04

There is a button on my App that calls useNavigate to change the URI location. I notice that it pushes the URI when pressed repeatedly.

How to get it to only push if the new URI is different from the current URI?

const navigate = useNavigate();
<div onClick={() => navigate("/home")}>
  Button
</div>

The problem with the code above is that each time the div is clicked, /home is pushed to the URI history stack even if the current location is /home. So that if the user press the back button it would seem to have no effect.

CodePudding user response:

Check the target path against the current location.pathname and only issue the imperative navigation if not already on the same path.

Example:

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

...

const { pathname } = useLocation();
const navigate = useNavigate();


<button
  onClick={() => {
    if (pathname !== "/home") {
      navigate("/home");
    } else {
      console.log("Already Home");
    }
  }}
>
  Go Home
</button>

Edit how-to-get-usenavigate-to-push-only-if-the-new-uri-is-different-from-the-current

  • Related