mirror of
https://github.com/hanzoai/next.js.git
synced 2026-10-30 14:46:38 +00:00
The Link component initiates a prefetch whenever it enters the viewport, but currently the implementation works by setting an `isVisible` state to true, rerendering the component, and calling `router.prefetch` inside a `useEffect` hook. This extra render is not necessary — we can initiate the prefetch directly inside the IntersectionObserver's event handler. The bulk of the changes in this commit involve removing the use of the `useIntersection` abstraction and inlining the IntersectionObserver into the Link module. The removal of this indirection will make it easier to add more sophisticated scheduling improvements, like canceling the prefetch on viewport exit, and increasing the priority of the prefetch during hover.
65 lines
1.6 KiB
TypeScript
65 lines
1.6 KiB
TypeScript
'use client'
|
|
|
|
import Link from 'next/link'
|
|
import { useState } from 'react'
|
|
|
|
type PaginationConfig = {
|
|
start: number
|
|
end: number
|
|
}
|
|
|
|
export default function LinkCancellationPage() {
|
|
const [areLinksVisible, setLinksVisibility] = useState(false)
|
|
const [showMoreLinks, setShowMoreLinks] = useState(false)
|
|
|
|
return (
|
|
<>
|
|
<p>
|
|
This page is used to test that a prefetch scheduled when a Link enters
|
|
the viewport is cancelled when the Link exits. The visibility toggle
|
|
does not affect whether the links are mounted, only whether they are
|
|
visible (using the `hidden` attribute).
|
|
</p>
|
|
<label>
|
|
<input
|
|
type="checkbox"
|
|
checked={areLinksVisible}
|
|
onChange={() => setLinksVisibility(!areLinksVisible)}
|
|
/>
|
|
{areLinksVisible ? 'Hide' : 'Show'} Links
|
|
</label>
|
|
<ul id="links-container" hidden={!areLinksVisible}>
|
|
<Links start={1} end={7} />
|
|
{showMoreLinks ? (
|
|
<Links start={8} end={10} />
|
|
) : (
|
|
<li>
|
|
<form>
|
|
<button
|
|
id="show-more-links"
|
|
formAction={() => setShowMoreLinks(true)}
|
|
>
|
|
Show more links
|
|
</button>
|
|
</form>
|
|
</li>
|
|
)}
|
|
</ul>
|
|
</>
|
|
)
|
|
}
|
|
|
|
function Links({ start, end }: PaginationConfig) {
|
|
const links: Array<React.ReactNode> = []
|
|
for (let pageNumber = start; pageNumber <= end; pageNumber++) {
|
|
links.push(
|
|
<li key={pageNumber}>
|
|
<Link href={'/cancellation/' + pageNumber}>
|
|
Link to page {pageNumber}
|
|
</Link>
|
|
</li>
|
|
)
|
|
}
|
|
return links
|
|
}
|