Files
ccd76c961a feat: useLinkStatus (#77300)
# `useLinkStatus` Hook

The `useLinkStatus` hook is primarily useful when:

- Links have `prefetch={false}` set
- Navigation occurs before prefetching has completed
- When React decides to [skip the loading
state](https://react.dev/reference/react/useTransition#preventing-unwanted-loading-indicators)
and https://github.com/vercel/next.js/issues/69625

It provides loading state feedback during these navigation transitions,
preventing pages from appearing "frozen" while new content loads.

## Usage

`useLinkStatus` can be called from any descendant component of `Link`
and it returns `{ pending: true }` before history has updated. After the
URL updates, it returns `{ pending: false }`.

```jsx
// When prefetching is disabled
<Link href="/dashboard/reports" prefetch={false}>
  Reports <LoadingIndicator />
</Link>

function LoadingIndicator() {
  const { pending } = useLinkStatus();
  return pending ? <Spinner /> : null;
}
```

## Notes

- If the link has been prefetched, pending change will be skipped and
remain `{ pending: false }`.
- If `useLinkStatus` is not under any `Link`, it will always return `{
pending: false }`.
- `useLinkStatus` currently does not support Pages Router, so it will
always return `{ pending: false }` in Pages Router.
- When you click multiple links in a short period, only the last link's
pending state is shown

---------

Co-authored-by: Andrew Clark <[email protected]>
2025-03-24 15:50:36 -07:00

27 lines
536 B
TypeScript

// This component delays rendering to simulate a slow page load
async function PostContent({ id }: { id: string }) {
await new Promise((resolve) => setTimeout(resolve, 3000))
return (
<div>
<h1>Post {id}</h1>
<p>This is post {id}</p>
<p>Posted on: {Date.now()}</p>
</div>
)
}
export default async function PostPage({
params,
}: {
params: Promise<{ id: string }>
}) {
const { id } = await params
return (
<div data-testid={`post-${id}-page`}>
<PostContent id={id} />
</div>
)
}