From eb74a28fcb78f934a3f0e030f9930332d46b9a4e Mon Sep 17 00:00:00 2001 From: SukkaW Date: Sun, 13 Mar 2022 20:41:48 +0800 Subject: [PATCH] fix(#35286): reset visible state when link href changed --- packages/next/client/link.tsx | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/packages/next/client/link.tsx b/packages/next/client/link.tsx index 9bb634d251adc02..58971eafcdaee19 100644 --- a/packages/next/client/link.tsx +++ b/packages/next/client/link.tsx @@ -219,6 +219,8 @@ function Link(props: React.PropsWithChildren) { } }, [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') { @@ -243,11 +245,21 @@ function Link(props: React.PropsWithChildren) { } 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) @@ -256,7 +268,7 @@ function Link(props: React.PropsWithChildren) { } } }, - [childRef, setIntersectionRef] + [as, childRef, href, resetVisible, setIntersectionRef] ) React.useEffect(() => { const shouldPrefetch = isVisible && p && isLocalURL(href)