서버에서 데이터 읽기: useQuery

유현지·2022년 6월 29일
0

React-Query

목록 보기
2/2

Read

useQuery: 서버에서 데이터를 읽을 때

function Todos() {
  const { isLoading, isError, data, error } = useQuery('todos', fetchTodoList);

  if (isLoading) return <span>Loading...</span>

  if (isError) return <span>Error: {error.message}</span>

  // We can assume by this point that `isSuccess === true`

  return (
    <ul>
      {data.map((todo) => (
        <li key={todo.id}>{todo.title}</li>
      ))}
    </ul>
  );
}

Query Data Flow

이미지출처 | 우아한 Tec Youtube

Query state

  • fresh: 신선한 상태일 때 refetch 하지 않는다.
  • stale: 신선하지 않은 상태일 때 아래의 경우에 refetch 한다.

    Active

    • New instances of the query mount
    • The window is refocused
    • The network is reconnected.
    • The query is optionally configured with a refetch interval.

staleTime vs cachingTime

  • staleTime
    • 화면 상에 보일 때 (mount, active)
    • 쿼리 데이터가 fresh 에서 stale 로 바뀌는 시간
    • 기본값: 0
  • cacheTime
    • 화면에서 내려갔을 때 (unmount, inacitve)
    • 메모리에 쿼리 데이터를 캐싱해두는 시간
    • 기본값: 5분

isLoading vs isFetching

  • isLoading
    • 없는데 가져올 때
    • 데이터가 텅 비어있고, 처음으로 데이터를 패칭할 때
  • isFetching
    • 있는데 덮어쓸 때
    • 데이터가 비어있지 않고, refetch 할 때 즉, 캐시가 있는 상태
      • initialData를 설정해주었거나 이미 패치된 데이터가 있을 때
      • 이땐 로딩 스피너를 보여주지 말고 fallback으로 신선하지 않더라도 데이터를 보여주고 있는 것 이 좋음
      • 그래도 가져오는 중인거 티내고 싶을 때는 데이터는 살려두고 알림을 추가하기



0개의 댓글