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 96ae758
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
11 changes: 6 additions & 5 deletions packages/next/client/image.tsx
Expand Up @@ -417,11 +417,12 @@ export default function Image({
isLazy = false
}

const [setIntersection, isIntersected, resetIntersected] = useIntersection<HTMLImageElement>({
rootRef: lazyRoot,
rootMargin: lazyBoundary,
disabled: !isLazy,
})
const [setIntersection, isIntersected, resetIntersected] =
useIntersection<HTMLImageElement>({
rootRef: lazyRoot,
rootMargin: lazyBoundary,
disabled: !isLazy,
})
const isVisible = !isLazy || isIntersected

const wrapperStyle: JSX.IntrinsicElements['span']['style'] = {
Expand Down
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 96ae758

Please sign in to comment.