๐Ÿ–ฅFrontEnd/React

tanstack query ํŽ˜์ด์ง€๋„ค์ด์…˜์‹œ ์‚ฌ์šฉ์ž ๊ฒฝํ—˜ ๊ฐœ์„ ํ•˜๊ธฐ, prefetching

hellohailie 2025. 1. 1. 23:51
๋ฐ˜์‘ํ˜•

 

tanstack query๋ฅผ ์‚ฌ์šฉํ•ด์„œ ๋ฐ์ดํ„ฐ ํŒจ์นญ์„ ํ•˜๋Š”๋ฐ ํŽ˜์ด์ง€๋„ค์ด์…˜์„ ๊ตฌํ˜„ํ•  ๋•Œ, ๋‹ค์Œ ํŽ˜์ด์ง€๋กœ ์ด๋™์„ ํ• ๋•Œ๋งˆ๋‹ค ๋กœ๋”ฉ ํ™”๋ฉด์ด ์‚ด์ง ๋ณด์ด๋Š” ๊ฒƒ์„ ๊ฐœ์„ ํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” prefetching ์„ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค. 

 

prefetching์„ ์‚ฌ์šฉํ•˜๋ฉด ๋ง ๊ทธ๋Œ€๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฏธ๋ฆฌ ๊ฐ€์ ธ์™€์„œ ์บ์‹œ์— ๋„ฃ๊ณ  ์‚ฌ์šฉ์ž๊ฐ€ ๋กœ๋”ฉ ํ™”๋ฉด์„ ๋ณด์ง€ ์•Š๋„๋ก ํ•  ์ˆ˜ ์žˆ๋‹ค. 

 


 

prefetchQuery๋Š” QueryClient ์˜ ๋ฉ”์†Œ๋“œ์ด๊ณ , useQueryClient ํ›…์„ ์จ์„œ ๊ทธ QueryClient๋ฅผ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ๋‹ค. 

 

์ƒํƒœ ์—…๋ฐ์ดํŠธ๊ฐ€ ๋น„๋™๊ธฐ์ ์ด๋ผ ์—…๋ฐ์ดํŠธ๊ฐ€ ์ด๋ฏธ ์ ์šฉ๋˜์—ˆ๋Š”์ง€ ์ •ํ™•ํ•˜๊ฒŒ ์•Œ ์ˆ˜ ์—†๊ธฐ ๋•Œ๋ฌธ์— ๋‹ค์Œ ํŽ˜์ด์ง€ ๋ฒ„ํŠผ์˜ ํด๋ฆญ ์ด๋ฒคํŠธ์—์„œ prefetching์ด ์‹คํ–‰๋˜๋„๋ก ํ•˜์ง€ ์•Š๋Š”๊ฒŒ ์ข‹๋‹ค. 

๊ทธ๋ž˜์„œ ํ˜„์žฌ ํŽ˜์ด์ง€๊ฐ€ ๋ณ€๊ฒฝ๋  ๋•Œ๋งˆ๋‹ค useEffect๋ฅผ ์‚ฌ์šฉํ•ด์„œ prefetching๋˜๋„๋ก ํ•œ๋‹ค. 

 

useEffect(() => {
    if (currentPage < maxPostPage) {
      const nextPage = currentPage + 1;
      queryClient.prefetchQuery({
        queryKey: ["posts", nextPage],
        queryFn: () => fetchPosts(nextPage),
      });
    }
  }, [currentPage, queryClient]);

 

 

์ „์ฒด ์ฝ”๋“œ

import { useState, useEffect } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";

export function Posts() {
  const [currentPage, setCurrentPage] = useState(1);
  const [selectedPost, setSelectedPost] = useState(null);
  const queryClient = useQueryClient();

  useEffect(() => {
    if (currentPage < maxPostPage) {
      const nextPage = currentPage + 1;
      queryClient.prefetchQuery({
        queryKey: ["posts", nextPage],
        queryFn: () => fetchPosts(nextPage),
      });
    }
  }, [currentPage, queryClient]);

  const { data, isError, error, isLoading } = useQuery({
    queryKey: ["posts", currentPage],
    queryFn: () => fetchPosts(currentPage),
    staleTime: 2000,
  });

  if (isLoading) {
    return <h3>Loading...</h3>;
  }

  if (isError) {
    return (
      <>
        <h3>Error fetching data</h3>
        <p>{error.toString()}</p>
      </>
    );
  }
  
  .
  .
  .

 

 

์ฐธ๊ณ  ๋งํฌ)

https://tanstack.com/query/latest/docs/framework/react/guides/prefetching#prefetchquery--prefetchinfinitequery

 

Prefetching & Router Integration | TanStack Query React Docs

When you know or suspect that a certain piece of data will be needed, you can use prefetching to populate the cache with that data ahead of time, leading to a faster experience. There are a few differ...

tanstack.com

 

๋ฐ˜์‘ํ˜•