[React Query] 리액트 쿼리 useQuery 실용 편

김효선·2021년 11월 25일
18

React Query 사용기

목록 보기
2/5
post-thumbnail

이전 시리즈에서 더 나아가 useQuery를 실무에서 사용했던 경험을 적어보려한다.

🌟 QueryClient 의 defaultOptions 설정하기

  • QueryClient 에서 추가적으로 defaultOptions 를 적용할 수 있다.
  • refetchOnMount, refetchOnReconnect, refetchOnWindowFocus 는 기본적으로 true로 설정되어있는데 이렇게 defaultOptions 에서 false로 셋팅해두면 모든 쿼리들이 이 옵션에 영향을 받는다.
    (무분별한 refetch를 막기 위해 모두 false로 설정해두었고 상황에 따라 필요한 쿼리에만 true로 별도의 옵션을 적용해서 사용하고 있다.)
  • staleTime 이나 cacheTime 등 다양한 옵션을 더 넣을 수 있다.
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      refetchOnMount: false,
      refetchOnReconnect: false,
      refetchOnWindowFocus: false,
    }
  }
});

🌟 QueryKey 관리하기

  • 회사에선 컨벤션을 맞추기 위해 문자열 키를 사용하지 않고 배열 키를 사용하고 있다!
export const queryKeys = {
 todos: ['todos'] as const,
 todoById: (todoId: string) => ['todos', todoId] as const,
};

// 이런식으로 사용하면 된다.
useQuery(queryKeys.todos, fetchTodos);
useQuery(queryKeys.todoById(todoId), () => fetchTodoById(todoId));

🌟 useQuery 커스텀 훅 with TypeScript

  • 여러 컴포넌트에서 같은 요청을 해줘야하는 경우엔 커스텀 훅으로 만들어서 공통으로 사용하고 있다.
import { AxiosError } from 'axios';
import { useQuery, UseQueryOptions, UseQueryResult } from 'react-query';
import { fetchTodos } from 'src/api/todos';
import { TodoType } from 'src/types/todoType';
import { queryKeys } from 'src/types/commonType';

export default function useTodosQuery(
  options?: UseQueryOptions<TodoType[], AxiosError>
): UseQueryResult<TodoType[], AxiosError> {
  return useQuery(queryKeys.todos, fetchTodos, options);
}
  • 사용 예제 코드
import useTodosQuery from 'src/hooks/useTodosQuery';

//...
// option을 추가하지 않았을 경우
const { data, isLoading } = useTodosQuery(); 
// option을 추가할 경우
const { data, isLoading } = useTodosQuery({ staleTime: 60 * 1000 }); 

옵션을 주고 싶을 때 파라미터로 옵션을 넘기면 된다!

다음 편은 useMutation에 대해서 정리할 예정이다

profile
차근차근 나아가는 주니어 프론트엔드 개발자

0개의 댓글