Community

React Query에 usePrefetchQuery 훅이 추가되었습니다

usePrefetchQuery 가 React Query v5.47.0 버전(2024년 6월 25일 배포)에 추가되었습니다. (As-is) usePrefetchQuery 훅 예제를 직접 구현해야 했음 (아래는 공식 문서의 예제) function usePrefetchQuery(options) { const queryClient = useQueryClient() // This happens in render, but is safe to do because ensureQueryData // only fetches if there is no data in the cache for this query. This // means we know no observers are watching the data so the side effect // is not observable, which is safe. if (!queryClient.getQueryState(options.queryKey)) { queryClient.ensureQueryData(options).catch(() => { // Avoid uncaught error }) } } (To-be) 라이브러리에서 제공하는 usePrefetchQuery 사용 가능 import { usePrefetchQuery } from '@tanstack/react-query' function App() { usePrefetchQuery({ queryKey: ['articles'], queryFn: (...args) => { return getArticles(...args) }, }) // ... } 이 훅이 필요한 케이스는 여러 상황이 있겠지만, 공식 문서에서 설명하는 예시는 컴포넌트에 Suspense와 Prefetch를 동시에 사용할 때 입니다. 공식 문서에 게시물 & 댓글 컴포넌트에 usePrefetchQuery 를 적용한 예제가 있으니 확인해 보시면 좋을 것 같습니다. 참고로, usePrefetchInfiniteQuery 도 5.47.0 버전에 함께 추가되었습니다. https://tanstack.com/query/v5/docs/framework/react/guides/prefetching#prefetch-in-components

알림

알림이 없습니다