Why useEffect doesn't run on window.location.pathname changes?

Create a hook, something like:

const useReactPath = () => {
  const [path, setPath] = React.useState(window.location.pathname);
  const listenToPopstate = () => {
    const winPath = window.location.pathname;
    setPath(winPath);
  };
  React.useEffect(() => {
    window.addEventListener("popstate", listenToPopstate);
    return () => {
      window.removeEventListener("popstate", listenToPopstate);
    };
  }, []);
  return path;
};

Then in your component use it like this:

const path = useReactPath();
React.useEffect(() => {
  // do something when path changes ...
}, [path]);

Of course you'll have to do this in a top component.

Tags:

Reactjs