I use useEffect
to listen for a change in location.pathname
to auto-scroll back to the top of the page (router) when the route changes. As I have a page transition (that takes pageTransitionTime * 1000
seconds), I use a timer that waits for the page transition animation to occur before the reset takes place. However, on the first load/mount of the router (after a loading page), I do NOT want to wait for the animation as there is no page animation.
Observe the code below, which works exactly as intended:
useEffect(() => {
const timer = setTimeout(() => {
window.scrollTo(0,0)
}, firstVisit.app ? 0 : pageTransitionTime * 1000 )
return () => clearTimeout(timer)
}, [location.pathname, pageTransitionTime])
The error I face here is that firstVisit.app
isn't in the dependency array. I get this error on Terminal:
React Hook useEffect has a missing dependency: 'firstVisit.app'. Either include it or remove the dependency array react-hooks/exhaustive-deps
firstVisit.app
is a global redux variable that is updated in the same React component by another useEffect
, setting it to false
as soon as the router is mounted (this useEffect
has no dependency array, so it achieves it purpose instantly).
// UPON FIRST MOUNT, SET firstVisit.app TO FALSE
useEffect(() => {
if (firstVisit.app) {
dispatch(setFirstVisit({
...firstVisit,
app: false
}))
}
})
The problem is, when I include firstVisit.app
in the dependency array in the first useEffect
, the page will auto-reset scroll to (0,0) after pageTransitionTime, affecting the UX.
A bit of Googling lead me to find that I may need to memoize firstVisit.app
but I'm not entirely sure how or the logic behind doing so?