본문 바로가기
챌린지/패스트캠퍼스 공부 루틴 챌린지

패스트캠퍼스 챌린지 18일차 (React-Query)

by 무벅 2022. 2. 10.
반응형

22.2.10 (목) +18days

Overview

https://react-query.tanstack.com/overview

 

Overview

Overview React Query is often described as the missing data-fetching library for React, but in more technical terms, it makes fetching, caching, synchronizing and updating server state in your React applications a breeze. Motivation Out of the box, React a

react-query.tanstack.com

fetching or updating data

기존 상태 관리 라이브러리들은 fetching을 중요하게 생각하지 않았음

client state와 server state는 다름

다양한 고려 필요(Caching, multi request, update, out date, pagination ..)

Example Code

import { QueryClient, QueryClientProvider, useQuery } from 'react-query'
 
 const queryClient = new QueryClient()
 
 export default function App() {
   return (
     <QueryClientProvider client={queryClient}>
       <Example />
     </QueryClientProvider>
   )
 }
 
 function Example() {
   const { isLoading, error, data } = useQuery('repoData', () =>
     fetch('https://api.github.com/repos/tannerlinsley/react-query').then(res =>
       res.json()
     )
   )
 
   if (isLoading) return 'Loading...'
 
   if (error) return 'An error has occurred: ' + error.message
 
   return (
     <div>
       <h1>{data.name}</h1>
       <p>{data.description}</p>
       <strong>👀 {data.subscribers_count}</strong>{' '}
       <strong>✨ {data.stargazers_count}</strong>{' '}
       <strong>🍴 {data.forks_count}</strong>
     </div>
   )
 }

Installation

$ npm i react-query
# or
$ yarn add react-query

Quick Start

This example very briefly illustrates the 3 core concepts of React Query:

Devtools

The devtools are bundle split into the react-query/devtools package. No need to install anything extra, just:

import { ReactQueryDevtools } from 'react-query/devtools'

Floating Mode

Floating Mode will mount the devtools as a fixed, floating element in your app and provide a toggle in the corner of the screen to show and hide the devtools. This toggle state will be stored and remembered in localStorage across reloads.

import { ReactQueryDevtools } from 'react-query/devtools'
 
 function App() {
   return (
     <QueryClientProvider client={queryClient}>
       {/* The rest of your application */}
       <ReactQueryDevtools initialIsOpen={false} />
     </QueryClientProvider>
   )
 }

Comparison

https://react-query.tanstack.com/comparison

 

Comparison | React Query vs SWR vs Apollo vs RTK Query

2 Render Optimization - React Query has excellent rendering performance. It will only re-render your components when a query is updated. For example because it has new data, or to indicate it is fetching. React Query also batches updates together to make s

react-query.tanstack.com

Important Defaults

기본 설정

staleTime, refetchOnWindowFocus, refetchOnMount, refetchonReConnet, refetchInterval, cacheTime(5 minutes), retry(3), retryDelay

Queries

https://react-query.tanstack.com/guides/queries

unique key / function

refetching, caching, sharing by key

result: status, error, data, isFetching(background fetching 도..)

Query Basics

A query is a declarative dependency on an asynchronous source of data that is tied to a unique key. A query can be used with any Promise based method (including GET and POST methods) to fetch data from a server. If your method modifies data on the server, we recommend using Mutations instead.

To subscribe to a query in your components or custom hooks, call the useQuery hook with at least:

  • unique key for the query
  • A function that returns a promise that:
    • Resolves the data, or
    • Throws an error
import { useQuery } from 'react-query'
 
 function App() {
   const info = useQuery('todos', fetchTodoList)
 }

Query Keys

https://react-query.tanstack.com/guides/query-keys

string / Array of many strings and nested objects

Array로 인식 / 객체 내부의 순서 무관 / Array의 순서는 유의미

Query Functions

https://react-query.tanstack.com/guides/query-functions

returns a promise (resolve the data | throw an error)

Query Keys이 params로 넘어옴

useQuery에 params 대신 객체를 넘길 수도 있음

useQuery({queryKey, queryFn, config})

Parallel Queries

https://react-query.tanstack.com/guides/parallel-queries

기본이 병렬 수행

Suspense 사용하면 제대로 동작안함(대신 useQueries 사용)

Dynamic Parallel Queries

useQueries([{queryKey, queryFn}]);

Dependent Queries

https://react-query.tanstack.com/guides/dependent-queries

enabled 옵션으로 조건 / 의존

Background Fetching Indicators

https://react-query.tanstack.com/guides/background-fetching-indicators

isFetching

useIsFetching

Window Focus Refetching

https://react-query.tanstack.com/guides/window-focus-refetching

Globally QueryClient

개별 useQuery

custom Focus Event(focusManager.setEventListener)

Disabling/Pausing Queries

https://react-query.tanstack.com/guides/disabling-queries

enabled: false

cached data가 있으면 success 상태 / 없으면 idle 상태

invalideteQueries / refetchQueries ignore

refech로 query를 trigger

Query Retries

https://react-query.tanstack.com/guides/query-retries

query fails defaults retries 3

retryDelay 기본은 back-off delay / Custom 가능 (ms)

Paginated / Lagged Queries

https://react-query.tanstack.com/guides/paginated-queries

keepPreviousData

Infinite Queries

https://react-query.tanstack.com/guides/infinite-queries

useInfiniteQuery

data: {pages, pageParams, fetchNextPage, hasNextPage ... }

Placeholder Query Data

https://react-query.tanstack.com/guides/placeholder-query-data

목록 조회시 가져온 일부 데이터를 상세 조회하기 전에 미리 보여줄 때..

Prefetching

https://react-query.tanstack.com/guides/prefetching

cache가 이미 있고 not invalidated 하다면 fetch 하지 않음

staleTime이 지났다면 fetch함

useQuery가 수행되지 않는다면, cacheTime 이후에 GC로 제거됨

Mutations

https://react-query.tanstack.com/guides/mutations

create / update / delete data

reset / side effect

Query Invalidation(invalidateQueries) / Updates(setQueryData)

 

정리1

React-Query

Server State ⇒ 기존 상태 관리 라이브러리에서 고려 X

개념 ⇒ Query / Mutate / Query Invalidate

Devtools ⇒ 자체 도구 존재

Example ⇒ 다양하게 참고 가능

정리2

Query ⇒ Query Keys / Query Fn

Parallel ⇒ useQueries

enalbed ⇒ dependent / Disable / Pause

Focus / Retry ⇒ 커스텀 가능

정리3

Paginated ⇒ keepPreviousData

무한 스크롤 ⇒ useInfiniteQuery

기본 값 ⇒ Placeholder / Initial

Mutations ⇒ change data / invalidate / set

 

 

 

 

22.2.10 +18days

 

 

 

 

https://bit.ly/37BpXiC

본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성되었습니다

 

 

 

 

 

 

반응형

댓글