Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

Why useEffect doesn't run on window.location.pathname changes? I get loc logged only once.

How can I make to run useEffect when pathname changes without any additional libraries?

  useEffect(() => {
    const loc = window.location.pathname
    console.log({ loc })
  }, [window.location.pathname])
like image 884
karolis2017 Avatar asked Oct 17 '19 23:10

karolis2017


People also ask

How do you run useEffect when state changes?

Use the useEffect hook to listen for state changes in React. You can add the state variables you want to track to the hook's dependencies array and the logic in your useEffect hook will run every time the state variables change. Copied!

Does useEffect get called on state change?

However, it is important to understand that the useEffect will get called after our page is rendered. From our code above, whenever our state changes, the useEffect will be called. The state has a default value of 0 , and whenever the default value changes, useEffect will be re-rendered.

How do I use the Windows location pathname in React?

If you need to access the path, use window. location. pathname . The pathname property returns a string containing the path of the URL for the location.

Does useEffect always run on Mount?

Important: the useEffect hook will always run on mount regardless of if there is anything in its dependency array.


1 Answers

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.

like image 71
Rafael Mora Avatar answered Oct 04 '22 19:10

Rafael Mora