How to invoke a function on every redirect using react-router-dom

I want to check for cookies every time a user gets redirected to a different Route. What would be the most conventional way to do this besides coding the function each time at the top of the main component which each Route loads?

>Solution :

You can use the useLocation and the useEffect hook:

function App() {
  let location = useLocation();

  useEffect(() => {
    //do your stuff
  }, [location]);

  return (
    // ...
  );
}

Leave a Reply