In react how to call a function on reaching a specific URL in the browser?

679 Views Asked by At

I'm using window.location.href to fetch url from the browser. As soon as the specified "url" is reached, it should call the fuction abc(), somewhat like below:

if (window.location.href === "url") {
  abc(); //calls the function abc
}

function abc () {
  //code..
}

How do I do it the right way?

2

There are 2 best solutions below

0
EvoluWil On BEST ANSWER

you can use this

useEffect(() => {
 if(window.location.href === 'url'){
  abc()
 }
},[window.location.href])
0
Colin Hale On

I would make some hook that does that for you. Example:

const useAbcHook = () => {
  const location = useLocation()

  useEffect(() => {
   if(location.pathname === "mychoiceurl"){
    abc()
    }
  },
  [url]
}

Then to use the hook

const MyComp = () => {
  useAbcHook()
  return(<div>....</div>)
}