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])
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!
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.
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.
Important: the useEffect hook will always run on mount regardless of if there is anything in its dependency array.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With