usePrefetch() - Next.js

A react hook to prefetch multiple routes at once and returns router

0 views
lib/usePrefetch.ts
import { useRouter } from 'next/router';
import { useEffect } from 'react';
 
const usePrefetch = (paths: string[]) => {
  const router = useRouter();
  useEffect(() => {
    paths.forEach((path) => {
      router.prefetch(path);
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  return router;
};
 
export default usePrefetch;

This react hook can come handy when you want to prefetch multiple routes at once.

For example, if you are building a command palette for your application that helps you navigate to different pages, you can use this hook to prefetch the pages.

components/CommandPalette.tsx
import usePrefetch from '@/lib/usePrefetch'
 
const CommandPalette = () => {
	const {data: notes, error} = useSWRImmutable('/api/...')
	const router = usePrefetch([...notes.map(note => note.url)])
	const commands = [
		...
	]
	return (
		<CommandPalette commands={commands} />
	);
};
}
 
export default CommandPalette

Note: This hook can only be used with Next.js