Skip to content

Commit

Permalink
feat: add useNextLinkProps
Browse files Browse the repository at this point in the history
  • Loading branch information
himself65 committed Jan 20, 2024
1 parent b3d9a37 commit 49dafad
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
25 changes: 25 additions & 0 deletions docs/src/pages/use-next-link-props.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
---
title: useNextLinkProps
---

# useNextLinkProps

```tsx
"use client";
import { useNextLinkProps } from 'foxact/use-next-link-props'
import Link from 'next/link'

export default function Page() {
const { isPending, linkProps } = useNextLinkProps({
href: '/about',
})
return (
<div>
{isPending && <div>Loading...</div>}
<Link {...linkProps}>
About
</Link>
</div>
);
}
```
29 changes: 29 additions & 0 deletions src/use-next-link-props/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import 'client-only';
import type { LinkProps } from 'next/link'
import { useCallback, useEffect, useMemo, useState } from 'react'
import type { MouseEvent } from 'react'
import { usePathname } from 'next/navigation'

export type ExtraProps = {
isPending: boolean
}

export const useNextLinkProps = (props: LinkProps): LinkProps & ExtraProps => {
const pathname = usePathname();
const [targetPathname, setTargetPathname] = useState(() => pathname);
useEffect(() => {
setTargetPathname(pathname)
}, [pathname])
const onClick = useCallback((event: MouseEvent<HTMLAnchorElement>) => {
setTargetPathname(new URL(event.currentTarget.href).pathname);
return props.onClick?.(event);
}, [props.onClick]);
const isPending = targetPathname !== pathname;
return useMemo(() => {
return {
...props,
onClick,
isPending
}
}, [props, onClick, isPending])
}

0 comments on commit 49dafad

Please sign in to comment.