Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(waku/router): prefetch on view (<Link />) #672

Merged
merged 4 commits into from
Apr 26, 2024
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 29 additions & 1 deletion packages/waku/src/router/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@
notPending?: ReactNode;
children: ReactNode;
unstable_prefetchOnEnter?: boolean;
unstable_prefetchOnView?: boolean;
bysxx marked this conversation as resolved.
Show resolved Hide resolved
} & Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'href'>;

export function Link({
Expand All @@ -152,6 +153,7 @@
pending,
notPending,
unstable_prefetchOnEnter,
unstable_prefetchOnView,
...props
}: LinkProps): ReactElement {
const router = useContext(RouterContext);
Expand All @@ -160,12 +162,38 @@
: () => {
throw new Error('Missing Router');
};
const prefetchRoute = router

Check warning on line 165 in packages/waku/src/router/client.ts

View workflow job for this annotation

GitHub Actions / test

The 'prefetchRoute' conditional could make the dependencies of useEffect Hook (at line 196) change on every render. To fix this, wrap the initialization of 'prefetchRoute' in its own useMemo() Hook
? router.prefetchRoute
: () => {
throw new Error('Missing Router');
};
const [isPending, startTransition] = useTransition();
const ref = useRef<HTMLAnchorElement>(null);
bysxx marked this conversation as resolved.
Show resolved Hide resolved

useEffect(() => {
if (unstable_prefetchOnView && ref.current) {
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const url = new URL(to, window.location.href);
if (url.href !== window.location.href) {
const route = parseRoute(url);
prefetchRoute(route);
}
}
});
},
{ threshold: 0.1 },
);

observer.observe(ref.current);

return () => {
observer.disconnect();
};
}
}, [unstable_prefetchOnView, prefetchRoute, to, ref]);
bysxx marked this conversation as resolved.
Show resolved Hide resolved
const onClick = (event: MouseEvent<HTMLAnchorElement>) => {
event.preventDefault();
const url = new URL(to, window.location.href);
Expand Down Expand Up @@ -198,7 +226,7 @@
: props.onMouseEnter;
const ele = createElement(
'a',
{ ...props, href: to, onClick, onMouseEnter },
{ ...props, href: to, onClick, onMouseEnter, ref },
children,
);
if (isPending && pending !== undefined) {
Expand Down
Loading