i need to re render a component in my app here is what i have done
let path = window.location.href;
useEffect(() => {
alert("changed");
}, [window.location.href]);
i am using window.history.pushState(null, null, window.location.pathname + "some url" );in one
of child component
which i need to detect in this above parent component but i am not getting alert("changed") every time there is change in url
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.