DEV Community

Discussion on: React progress bar on page load/route change(both Next js & CRA)

Collapse
 
ankitsahu01 profile image
Ankit Sahu

Awesome. But there is a little problem, when we click on same link twice then top progress bar starts and will never stop.
This is happening bcoz the current location and previous location are same and thats by the useEffect with dependency prevLoc not invoking.
To get rid of it ---->

useEffect(() => {
setPrevLoc(location.pathname);
setProgress(true);
if(location.pathname===prevLoc){
setPrevLoc(''); //To fix same path infinite progress bar loading
}
}, [location]);

Collapse
 
ataparvinghods profile image
Ata Parvin Ghods • Edited

Thank you so much ankit!
I edited the post, much appreciated ❤

Collapse
 
ankitsahu01 profile image
Ankit Sahu • Edited

Most Welcome... one more thing is that the code which i wrote above having a Warning -> React Hook useEffect has a missing dependency: 'prevLoc'

To get rid of it simply modify few more things --->

const [progress, setProgress] = useState(false);
const [prevLoc, setPrevLoc] = useState({});
const location = useLocation();

useEffect(() => {
setPrevLoc(location);
setProgress(true);
window.scrollTo(0, 0); //Go to top on every page load
}, [location]);

useEffect(() => {
setProgress(false);
}, [prevLoc]);