HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
🚀
개발 노트
/
🕜
React query
/
🧨
Udemy 강의
/
📒
Blog-em Ipsum
📒

Blog-em Ipsum

React query 소개

  • React의 Server State를 관리하는 라이브러리
  • Loading / Error sates, Prefetching, De-duplication of requests, Pagination / Infinie scroll, Mutations, Retry on error, Callbacks
 
※ Client State: 웹 브라우저의 세션과 관련 (테마, 언어 등)
 

useQuery의 반환값

data, isLoading, isFetching, isError, error 등
 

isFetching vs isLoading

  • isFetching
    • 비동기 쿼리가 해결되지 않았음
      “the async query function hasn't yet resolved”
  • isLoading
    • 데이터를 가져오는 상태에 있음 no cached data, plus isFetching
notion image
 

Stale Data

  • 만료 데이터
  • 데이터 리페칭(Refetching)은 만료된 데이터에서만 실행된다.
    • 예) 컴포넌트 리마운트, 윈도우 리포커스 등
  • staleTime translates to "max age"
  • How to tolerate data potentially being out of date?
  • staleTime의 기본값은 왜 0일까?
    • ⇒ “데이터는 항상 만료 상태이므로, 서버에서 다시 가져와야 한다고 가정하는 것”
      “실수로 유저에게 만료된 데이터를 제공할 가능성이 줄어든다”
 

staleTime vs cacheTime

  • staleTime is for re-fetching
    • 데이터가 사용 가능한 상태로 유지되는 시간.
      특정 트리거에서 쿼리 데이터를 다시 가져올지를 결정.
      stateTime이 지나면 서버에서 유효성을 확인해야 한다.
  • cahceTime은 useQuery가 활성화된 후 경과한 시간
  • Cache is for data that might be re-used later
    • query goes into “cold storage” if there’s no active useQuery
    • cache data expires after cacheTime (default: five minutes)
  • After the cache expires, the data is garbage collected
  • Cache is backup data to display while fetching
 

Data for queries with known keys only refetched upon trigger

Example triggers:
  • component remount
  • window refocus
  • runing refetch function
  • automated refetch
  • query invalidation after a mutation
 

query key as Array

const { data, isLoading, isError, error } = useQuery( ["posts", currentPage], () => fetchPosts(currentPage), { staleTime: 2000, } );
 
의존배열 ["posts", currentPage]의 값이 변경되면
() ⇒ fetchPosts(currentPage)가 재선언된다.