Unverified Commit c94753cf authored by Delba de Oliveira's avatar Delba de Oliveira Committed by GitHub

Docs: Update `useLinkStatus` API reference (#78022)

Updating the docs after playing around with `useLinkStatus`:
https://github.com/vercel/next-app-router-playground/pull/184
Closes: https://linear.app/vercel/issue/DOC-4514/update-docs

Main changes:

- Update introduction
- Simplify example
- Add example for gracefully handling fast navigations (avoiding UI
flash)
parent 5b243a2d
--- ---
title: useLinkStatus title: useLinkStatus
description: API Reference for the useLinkStatus hook. description: API Reference for the useLinkStatus hook.
related:
title: Next Steps
description: Learn more about the features mentioned in this page by reading the API Reference.
links:
- app/api-reference/components/link
- app/api-reference/file-conventions/loading
--- ---
`useLinkStatus` is a **Client Component** hook that lets you track the loading state of a `Link` component during navigation. It can be used to show loading indicators during page transitions, especially when [prefetching](/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching) is disabled, or the linked route does not have any loading states. The `useLinkStatus` hook lets you tracks the **pending** state of a `<Link>`. You can use it to show inline visual feedback to the user (like spinners or text glimmers) while a navigation to a new route completes.
`useLinkStatus` is useful when:
- [Prefetching](/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching) is disabled or in progress meaning navigation is blocked.
- The destination route is dynamic **and** doesn't include a [`loading.js`](/docs/app/api-reference/file-conventions/loading) file that would allow an instant navigation.
```tsx filename="app/loading-indicator.tsx" switcher ```tsx filename="app/loading-indicator.tsx" switcher
'use client' 'use client'
...@@ -12,7 +23,9 @@ import { useLinkStatus } from 'next/link' ...@@ -12,7 +23,9 @@ import { useLinkStatus } from 'next/link'
export default function LoadingIndicator() { export default function LoadingIndicator() {
const { pending } = useLinkStatus() const { pending } = useLinkStatus()
return pending ? <span>⌛</span> : null return pending ? (
<div role="status" aria-label="Loading" className="spinner" />
) : null
} }
``` ```
...@@ -23,7 +36,9 @@ import { useLinkStatus } from 'next/link' ...@@ -23,7 +36,9 @@ import { useLinkStatus } from 'next/link'
export default function LoadingIndicator() { export default function LoadingIndicator() {
const { pending } = useLinkStatus() const { pending } = useLinkStatus()
return pending ? <span>⌛</span> : null return pending ? (
<div role="status" aria-label="Loading" className="spinner" />
) : null
} }
``` ```
...@@ -81,13 +96,11 @@ const { pending } = useLinkStatus() ...@@ -81,13 +96,11 @@ const { pending } = useLinkStatus()
| -------- | ------- | -------------------------------------------- | | -------- | ------- | -------------------------------------------- |
| pending | boolean | `true` before history updates, `false` after | | pending | boolean | `true` before history updates, `false` after |
## Examples ## Example
### Improving the user experience when navigating with new query parameters
In this example, navigating between categories updates the query string (e.g. ?category=books). However, the page may appear unresponsive because the `<PageSkeleton />` fallback won't replace the existing content (see [preventing unwanted loading indicators](https://react.dev/reference/react/useTransition#preventing-unwanted-loading-indicators)). ### Inline loading indicator
You can use the `useLinkStatus` hook to render a lightweight loading indicator next to the active link and provide immediate feedback to the user while the data is being fetched. It's helpful to add visual feedback that navigation is happening in case the user clicks a link before prefetching is complete.
```tsx filename="app/components/loading-indicator.tsx" switcher ```tsx filename="app/components/loading-indicator.tsx" switcher
'use client' 'use client'
...@@ -96,7 +109,9 @@ import { useLinkStatus } from 'next/link' ...@@ -96,7 +109,9 @@ import { useLinkStatus } from 'next/link'
export default function LoadingIndicator() { export default function LoadingIndicator() {
const { pending } = useLinkStatus() const { pending } = useLinkStatus()
return pending ? <span>⌛</span> : null return pending ? (
<div role="status" aria-label="Loading" className="spinner" />
) : null
} }
``` ```
...@@ -107,105 +122,102 @@ import { useLinkStatus } from 'next/link' ...@@ -107,105 +122,102 @@ import { useLinkStatus } from 'next/link'
export default function LoadingIndicator() { export default function LoadingIndicator() {
const { pending } = useLinkStatus() const { pending } = useLinkStatus()
return pending ? <span>⌛</span> : null return pending ? (
<div role="status" aria-label="Loading" className="spinner" />
) : null
} }
``` ```
```tsx filename="app/page.tsx" switcher ```tsx filename="app/shop/layout.tsx" switcher
import { useSearchParams } from 'next/navigation'
import Link from 'next/link' import Link from 'next/link'
import { Suspense } from 'react' import LoadingIndicator from './components/loading-indicator'
import LoadingIndicator from './loading-indicator'
const links = [
{ href: '/shop/electronics', label: 'Electronics' },
{ href: '/shop/clothing', label: 'Clothing' },
{ href: '/shop/books', label: 'Books' },
]
function MenuBar() { function Menubar() {
return ( return (
<div> <div>
<Link href="?category=electronics"> {links.map((link) => (
Electronics <LoadingIndicator /> <Link key={link.label} href={link.href}>
</Link> {link.label} <LoadingIndicator />
<Link href="?category=clothing"> </Link>
Clothing <LoadingIndicator /> ))}
</Link>
<Link href="?category=books">
Books <LoadingIndicator />
</Link>
</div> </div>
) )
} }
async function ProductList({ category }: { category: string }) { export default function Layout({ children }: { children: React.ReactNode }) {
const products = await fetchProducts(category)
return ( return (
<ul> <div>
{products.map((product) => ( <Menubar />
<li key={product}>{product}</li> {children}
))} </div>
</ul>
) )
} }
```
```jsx filename="app/shop/layout.js" switcher
import Link from 'next/link'
import LoadingIndicator from './components/loading-indicator'
export default async function ProductCategories({ const links = [
searchParams, { href: '/shop/electronics', label: 'Electronics' },
}: { { href: '/shop/clothing', label: 'Clothing' },
searchParams: Promise<{ { href: '/shop/books', label: 'Books' },
category: string ]
}>
}) {
const { category } = await searchParams
function Menubar() {
return ( return (
<Suspense fallback={<PageSkeleton />}> <div>
<MenuBar /> {links.map((link) => (
<ProductList category={category} /> <Link key={link.label} href={link.href}>
</Suspense> {link.label} <LoadingIndicator />
</Link>
))}
</div>
) )
} }
```
```jsx filename="app/page.js" switcher export default function Layout({ children }) {
import { useSearchParams } from 'next/navigation'
import Link from 'next/link'
import { Suspense } from 'react'
import LoadingIndicator from './loading-indicator'
function MenuBar() {
return ( return (
<div> <div>
<Link href="?category=electronics"> <Menubar />
Electronics <LoadingIndicator /> {children}
</Link>
<Link href="?category=clothing">
Clothing <LoadingIndicator />
</Link>
<Link href="?category=books">
Books <LoadingIndicator />
</Link>
</div> </div>
) )
} }
```
async function ProductList({ category }) { ## Gracefully handling fast navigation
const products = await fetchProducts(category)
return ( If the navigation to a new route is fast, users may see an unecessary flash of the loading indicator. One way to improve the user experience and only show the loading indicator when the navigation takes time to complete is to add an initial animation delay (e.g. 100ms) and start the animation as invisible (e.g. `opacity: 0`).
<ul>
{products.map((product) => ( ```css filename="app/styles/global.css"
<li key={product}>{product}</li> .spinner {
))} /* ... */
</ul> opacity: 0;
) animation:
fadeIn 500ms 100ms forwards,
rotate 1s linear infinite;
} }
export default async function ProductCategories({ searchParams }) { @keyframes fadeIn {
const { category } = await searchParams from {
opacity: 0;
}
to {
opacity: 1;
}
}
return ( @keyframes rotate {
<Suspense fallback={<PageSkeleton />}> to {
<MenuBar /> transform: rotate(360deg);
<ProductList category={category} /> }
</Suspense>
)
} }
``` ```
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment