Advanced Data Synchronization Technique
Implement query prefetching on a Next.js page link hover, demonstrating how to use React Query's prefetchQuery function to preload data for a faster user experience.
import { prefetchQuery } from 'react-query';
import { fetchPokemon } from '../api/pokemon';
First, import necessary functions. prefetchQuery from React Query is used for prefetching, and fetchPokemon is a hypothetical API call function.
const PokemonLink = ({ id, name }) => {
return (
<div onMouseEnter={() => prefetchPokemonData(id)}>
{name}
</div>
);
};
This React component represents a link for a Pokemon. It uses onMouseEnter to trigger prefetching.
const prefetchPokemonData = async (id) => {
await prefetchQuery(['pokemon', id], () => fetchPokemon(id));
};
This function prefetches data for a Pokemon by its ID. It uses prefectQuery with a unique key ['pokemon', id] and the fetching function.