Skip to content

Commit

Permalink
fix(#35286): reset visible state when link href changed
Browse files Browse the repository at this point in the history
  • Loading branch information
SukkaW committed Mar 15, 2022
1 parent bc85e4a commit 4c7d014
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions packages/next/client/link.tsx
Expand Up @@ -219,6 +219,9 @@ function Link(props: React.PropsWithChildren<LinkProps>) {
}
}, [router, props.href, props.as])

const previousHref = React.useRef<string>(href)
const previousAs = React.useRef<string>(as)

let { children, replace, shallow, scroll, locale } = props

if (typeof children === 'string') {
Expand All @@ -243,11 +246,19 @@ function Link(props: React.PropsWithChildren<LinkProps>) {
}
const childRef: any = child && typeof child === 'object' && child.ref

const [setIntersectionRef, isVisible] = useIntersection({
const [setIntersectionRef, isVisible, resetVisible] = useIntersection({
rootMargin: '200px',
})

const setRef = React.useCallback(
(el: Element) => {
// Before the link getting observed, check if visible state need to be reset
if (previousAs.current !== as || previousHref.current !== href) {
resetVisible()
previousAs.current = as
previousHref.current = href
}

setIntersectionRef(el)
if (childRef) {
if (typeof childRef === 'function') childRef(el)
Expand All @@ -256,7 +267,7 @@ function Link(props: React.PropsWithChildren<LinkProps>) {
}
}
},
[childRef, setIntersectionRef]
[as, childRef, href, resetVisible, setIntersectionRef]
)
React.useEffect(() => {
const shouldPrefetch = isVisible && p && isLocalURL(href)
Expand Down

0 comments on commit 4c7d014

Please sign in to comment.