티스토리 뷰

TIL

TIL 230327 React-Query study with ChatGPT

2021bong 2023. 3. 28. 00:10

리액트 쿼리 공식문서가 표가 아니라서 보기 불편하길래 특별 선생님으로 ChatGPT를 초빙했다. 😀👏

 

useQuery

useQuery(queryKey, queryFn, options)
  • queryKey (required) : This parameter is a unique identifier for the query. It can be a string or an array of strings and/or objects. The queryKey is used to cache the query results and manage query state. it should be unique for each query. If the queryKey changes, the query will be invalidated and refetched. : 필수값이며 쿼리에 대한 식별자로 사용한다. 문자열, 배열, 오브젝트도 가능하며 쿼리키로 결과를 캐싱하거나 쿼리 값을 관리하는데 사용한다. 모두 다른 값으로 사용하는게 좋으며 쿼리키가 바뀐다면 쿼리가 유효하지 않거나 refectch 된다.
  • queryFn (required) : This parameter is a function that performs the actual data fetching for the query. It can be an async function that returns the data, a Promise that resolves to the data, or a synchronous function that returns the data. When the query is executed, queryFn is called to fetch the data. The data returned by queryFn is stored in the cache and made available to the component via the useQuery hook. The queryFn is called whenever the data needs to be refetched, such as after the cache has expired or the data has become stale. : 쿼리에 대한 실제 데이터 가져오기를 수행하는 함수다. 데이터를 반환하는 비동기 함수, resolve되면 데이터를 가져오는 Promise, 데이터를 반환하는 동기 함수일 수도 있다. 쿼리가 실행되면 queryFn가 호출돼 데이터를 가져온다. queryFn에서 반환된 데이터는 캐시에 저장되며 useQueryhook을 통해 컴포넌트에서 사용할 수 있게 된다. queryFn은 캐시가 만료되었거나 데이터가 데이터가 오래됐을 때와 같은 refetch가 필요할 때 호출된다.
  • options (optional) : This is an optional object that can be used to customize the query behavior. Here are some of the most commonly used options: 쿼리 동작 사용자 설정 옵션
    • enabled (default 'true') : A boolean value that determines whether the query should be enabled. If set to false, the query will not run until it is manually enabled. This can be useful for preventing unnecessary data fetching in certain circumstances.
    • retry (default '3') : An object that defines how the query should handle retries. It can contain properties such as maxAttempts, retryDelay, and retryOn. : 실패했을 때 재요청 하는 속성
    • refetchOnWindowFocus (default true): A boolean that determines whether the query should be refetched when the window regains focus after being blurred. This can be useful for ensuring that the data is up-to-date when the user returns to the page.
    • staleTime : The number of milliseconds that the query data can remain "stale" before it is refetched. This can help improve performance by reducing unnecessary data fetching.
    • cacheTime (default 5 * 60 * 1000) : The number of milliseconds that the query data should be cached. After this time, the query will be refetched.
    • onSuccess: A callback function that is called whenever the query succeeds. It can be used to update local state or trigger other side effects.
    • onError: A callback function that is called whenever the query fails. It can be used to handle errors or trigger other side effects.
    • onSettled: Functions that are called when the query settles (i.e. completes, whether it succeeded or failed).
    • select: A function that selects a specific piece of data from the query result. This can be useful for extracting a single value from a larger data object.
    • role: A string value that can be used to indicate the "role" or purpose of the data being fetched by the query. This can be useful for managing and optimizing your data fetching.

 

QueryClient

QueryClient를 생성해서 QueryClientProvider에 client로 넣어주고 가장 상위에 QueryClientProvider를 통해 감싸주면 리액트 쿼리를 사용할 수 있는 것 같다. 이렇게 하면 모든 하위 구성 요소가 쿼리를 실행하고 캐시를 관리하는 데 사용할 수 있는 훅을 통해 쿼리 클라이언트에 액세스할 수 있다고 한다.

import { QueryClient, QueryClientProvider } from 'react-query';

const queryClient = new QueryClient();

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      {/* Your app code here */}
    </QueryClientProvider>
  );
}

 

 

ReactQueryDevtools

실시간으로 쿼리를 검사하고 디버깅할 수 있는 ReactQueryDevtools를 제공한다. ReactQueryDevtools를 사용하면 화면에 아래에 생긴다.

import { QueryClient, QueryClientProvider } from 'react-query';
import { ReactQueryDevtools } from 'react-query/devtools';

const queryClient = new QueryClient();

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      {/* Your app code here */}
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  );
}

ReactQueryDevtools

 

다양한 Hooks

  1. useMutation: This hook is used to handle mutations, or operations that modify data on the server. It returns a mutation function that can be called to execute the mutation, as well as an object with information about the mutation's status and result. The useMutation hook provides options for handling optimistic updates, retrying failed requests, and more.
  2. useQueryClient: This hook is used to access the QueryClient instance from anywhere in your component tree. It can be used to execute queries manually or perform other cache management tasks. You can use this hook to execute queries outside of a component (e.g. in an event handler), manually invalidate queries, or update the cache directly. : useQueryClient에 액세스하고 쿼리를 수동으로 무효화하거나 캐시를 지우는 등의 캐시 관리 작업을 수행
  3. useIsFetching: This hook returns a boolean indicating whether any queries are currently being fetched. You can use this hook to display a loading indicator or disable UI elements while data is being fetched.
  4. useQueries: This hook is used to execute multiple queries in parallel. It returns an array of query results, as well as a function to manually trigger a refetch of all the queries. : 쿼리를 여러개 수행할 때 사용
  5. useInfiniteQuery: This hook allows you to fetch paginated data in an infinite-scrolling interface or you need to fetch a large amount of data in chunks. It works by fetching data in batches as the user scrolls through the page, and automatically manages caching and fetching new data as needed. It returns an object with information about the current page of data, as well as functions to fetch the next page or reset the query. : 무한 스크롤 구현할 때
  6. useQueryErrorResetBoundary: This hook allows you to handle errors that occur during query fetching in a more fine-grained manner. You can use this hook to wrap a group of components and reset any query errors that occur within that group of components, without affecting other queries in your application.
728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함