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 13, 2022
1 parent b21a1d9 commit eb74a28
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions packages/next/client/link.tsx
Expand Up @@ -219,6 +219,8 @@ function Link(props: React.PropsWithChildren<LinkProps>) {
}
}, [router, props.href, props.as])

const previousHref = React.useRef<{ href: string; as: string }>({ href, as })

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

if (typeof children === 'string') {
Expand All @@ -243,11 +245,21 @@ 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 (
previousHref.current.as !== as ||
previousHref.current.href !== href
) {
resetVisible()
previousHref.current = { href, as }
}

setIntersectionRef(el)
if (childRef) {
if (typeof childRef === 'function') childRef(el)
Expand All @@ -256,7 +268,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 eb74a28

Please sign in to comment.