https://github.com/bytekai/preload-next
A Preload Link Component for Next.js to allow for preloading of data before navigation on hover or when link is in view.
https://github.com/bytekai/preload-next
link nextjs preload
Last synced: about 1 month ago
JSON representation
A Preload Link Component for Next.js to allow for preloading of data before navigation on hover or when link is in view.
- Host: GitHub
- URL: https://github.com/bytekai/preload-next
- Owner: bytekai
- Created: 2023-05-01T04:03:23.000Z (about 3 years ago)
- Default Branch: main
- Last Pushed: 2023-06-10T10:07:04.000Z (about 3 years ago)
- Last Synced: 2025-03-21T20:35:52.064Z (about 1 year ago)
- Topics: link, nextjs, preload
- Language: TypeScript
- Homepage: https://preload-next-example.vercel.app
- Size: 135 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Preload Link NextJS
## Or rather prefetching, the terms confuse me.
A variant of the Link component in NextJS that will execute a preload function that is attached to the page to allow for preloading data on hover. Providing the illusion of a faster page load as the data is loaded when the user hovers over the link.
## Demo
https://preload-next-example.vercel.app
## Installation
```bash
yarn install preload-next
```
or
```bash
npm install preload-next
```
## Usage
pages/index.tsx
```jsx
import { LinkPreload } from "preload-next";
export const Header = () => {
return (
Header
Pokemon
);
};
const Home = () => {
return (
Hello
);
};
```
pages/pokemon.tsx
```jsx
import dynamic from "next/dynamic";
import { NextPageContext } from "next/types";
import { useQuery } from "react-query";
import { PreloadContext } from "./_app";
type Pokemon = {
name: string;
};
const getPokemons = async (): Promise => {
return new Promise((resolve) => {
setTimeout(async () => {
const response = await fetch("https://pokeapi.co/api/v2/pokemon");
resolve((await response.json()).results);
}, 500);
});
};
const PokemonPage = () => {
const { data: pokemons, isLoading } = useQuery("pokemon", getPokemons);
return (
Pokemon
{pokemons &&
pokemons.map((pokemon: any) => (
- {pokemon.name}
))}
{isLoading &&
- Loading...
}
);
};
const preload = async ({ queryClient }: PreloadContext) => {
if (!queryClient.getQueryCache().find("pokemon")) {
queryClient.prefetchQuery("pokemon", getPokemons);
}
};
const getInitialProps = async (ctx: NextPageContext) => {
if (typeof window === "undefined") {
const { QueryClient, dehydrate } = await import("react-query");
const queryClient = new QueryClient();
await queryClient.prefetchQuery("pokemon", getPokemons);
return {
dehydratedState: dehydrate(queryClient),
};
}
return {};
};
const PPage = dynamic(() => Promise.resolve(PokemonPage), {
ssr: false,
}) as any;
PPage.preload = preload;
PPage.getInitialProps = getInitialProps;
export default PPage;
```