React Query 공부 (7) - prefetching

JunSeok·2023년 2월 5일
0

react-query

목록 보기
7/11
post-thumbnail

prefetching

사람들이 원하는 데이터를 미리 알고 있다면, 그 데이터를 캐시에 미리 채움으로써 UX를 개선할 수 있다.
이를 위해 prefetching이라는 기술을 사용한다. 말 그대로 미리 fetching한다는 의미이다.

유의할 점은 데이터를 미리 fetching하는 것이기 때문에 자주 변하지 않는 데이터를 prefetching하는 것이 적절하다.

구현

queryClient의 prefetchQuery method를 사용할 것이다.
구현은 간단하다.

// useTreatments.tsx
import { queryKeys } from '../../../react-query/constants'

const getTreatments = async () => {
	const { data } = await apiInstance.get('/treatments')
    return data
}


export const usePrefetchTreatments = () => {
 	const queryClient = new QueryClient()
    queryClient.prefetchQuery(queryKeys.treatments, getTreatments)
}

prefetching할 함수를 만들고 export한 다음 index에서 실행시켜준다.
index에서 미리 prefetching 한 뒤에 유저가 treatment로 이동했을 때 기다림 없이 데이터를 바로 볼 수 있다.

// index.tsx
const Index = () => {
	usePrefetchTreatments()
    return (
      <p>home page</p>
    )
}

export default Index
profile
최선을 다한다는 것은 할 수 있는 한 가장 핵심을 향한다는 것

0개의 댓글