From 83512ea6f3dac0624554e765361148119cee5535 Mon Sep 17 00:00:00 2001 From: Alan Alickovic Date: Sat, 3 Aug 2024 20:15:54 +0200 Subject: [PATCH] add data prefetching --- .../discussions/components/discussions-list.tsx | 16 +++++++++++++++- docs/performance.md | 6 ++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/apps/react-vite/src/features/discussions/components/discussions-list.tsx b/apps/react-vite/src/features/discussions/components/discussions-list.tsx index 12aaf873..647b88b1 100644 --- a/apps/react-vite/src/features/discussions/components/discussions-list.tsx +++ b/apps/react-vite/src/features/discussions/components/discussions-list.tsx @@ -1,14 +1,18 @@ +import { useQueryClient } from '@tanstack/react-query'; + import { Link } from '@/components/ui/link'; import { Spinner } from '@/components/ui/spinner'; import { Table } from '@/components/ui/table'; import { formatDate } from '@/utils/format'; +import { getDiscussionQueryOptions } from '../api/get-discussion'; import { useDiscussions } from '../api/get-discussions'; import { DeleteDiscussion } from './delete-discussion'; export const DiscussionsList = () => { const discussionsQuery = useDiscussions(); + const queryClient = useQueryClient(); if (discussionsQuery.isLoading) { return ( @@ -39,7 +43,17 @@ export const DiscussionsList = () => { title: '', field: 'id', Cell({ entry: { id } }) { - return View; + return ( + { + // Prefetch the discussion data when the user hovers over the link + queryClient.prefetchQuery(getDiscussionQueryOptions(id)); + }} + to={`./${id}`} + > + View + + ); }, }, { diff --git a/docs/performance.md b/docs/performance.md index ea03b1fa..59472a47 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -87,3 +87,9 @@ Use `srcset` to load the most optimal image for the clients screen size. ### Web vitals Since Google started taking web vitals in account when indexing websites, you should keep an eye on web vitals scores from [Lighthouse](https://web.dev/measure/) and [Pagespeed Insights](https://pagespeed.web.dev/). + +### Data prefetching + +It is possible to prefetch data before the user navigates to a page. This can be done by using the `queryClient.prefetchQuery` method from the `@tanstack/react-query` library. This method allows you to prefetch data for a specific query. This can be useful when you know that the user will navigate to a specific page and you want to prefetch the data before the user navigates to the page. This can help to improve the performance of the application by reducing the time it takes to load the data when the user navigates to the page. + +[Data Prefetching Example Code](../apps/react-vite/src/features/discussions/components/discussions-list.tsx)