From 96ae7586c96d789418a5fa0e439d68af7399e1f2 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/image.tsx | 11 ++++++----- packages/next/client/link.tsx | 15 +++++++++++++-- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/packages/next/client/image.tsx b/packages/next/client/image.tsx index 0b889410c644a53..dd323e2af50c2f8 100644 --- a/packages/next/client/image.tsx +++ b/packages/next/client/image.tsx @@ -417,11 +417,12 @@ export default function Image({ isLazy = false } - const [setIntersection, isIntersected, resetIntersected] = useIntersection({ - rootRef: lazyRoot, - rootMargin: lazyBoundary, - disabled: !isLazy, - }) + const [setIntersection, isIntersected, resetIntersected] = + useIntersection({ + rootRef: lazyRoot, + rootMargin: lazyBoundary, + disabled: !isLazy, + }) const isVisible = !isLazy || isIntersected const wrapperStyle: JSX.IntrinsicElements['span']['style'] = { diff --git a/packages/next/client/link.tsx b/packages/next/client/link.tsx index 9bb634d251adc02..867669c2856ea3b 100644 --- a/packages/next/client/link.tsx +++ b/packages/next/client/link.tsx @@ -219,6 +219,9 @@ function Link(props: React.PropsWithChildren) { } }, [router, props.href, props.as]) + const previousHref = React.useRef(href) + const previousAs = React.useRef(as) + let { children, replace, shallow, scroll, locale } = props if (typeof children === 'string') { @@ -243,11 +246,19 @@ 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 (previousAs.current !== as || previousHref.current !== href) { + resetVisible() + previousAs.current = as + previousHref.current = href + } + setIntersectionRef(el) if (childRef) { if (typeof childRef === 'function') childRef(el) @@ -256,7 +267,7 @@ function Link(props: React.PropsWithChildren) { } } }, - [childRef, setIntersectionRef] + [as, childRef, href, resetVisible, setIntersectionRef] ) React.useEffect(() => { const shouldPrefetch = isVisible && p && isLocalURL(href)