ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [React.js] React Query 에 대해 (feat. SWR 과의 차이) -v3
    FrontEnd/React.js 2022. 12. 30. 15:21

    SWR, React Query 등장 이전

       Redux, MobX 등의 상태 관리 라이브러리는 클라이언트 상태 관리에는 유용하지만,  

      서버 상태와 동기화 되지 않았기 때문에 개발자들이 직접 상태를 업데이트 해줬어야 함.

    => SWR과 React Query는 이러한 불편함을 해소하기 위해 등장 

    • 선언적으로 프로그래밍 가능
    • 여러번 호출 된 동일한 API 요청은 한번만 실행
    • dirty해진 데이터는 적절한 시점에 알아서 업데이트
    • Global State 와 Server State의 관심사 분리
    •  

    최근 1년간 비교

    react-query가 swr을 앞지르고 있다.

    React query vs SWR

    • React Query

    React Query는 리액트 에플리케이션에 서버 상태를 가져와서, 캐싱|동기화|업데이트를 쉽게 해준다

    React Query is a library for managing async data in React. It is based on React Apollo’s client in a big way, but it has fewer features and is smaller.

    React Query provides a set of hooks and tools to fetch, cache, and update async data in React apps. In addition to the core hooks, React Query also provides some helpful utilities for Data Management, error handling, and pagination.

    Twitter, Lyft, Shopify, Spectrum Health Grand Rapids, Auth0 Docs, and Portainer, among other companies, uses React Query.
    • SWR 

    SWR은 먼저 캐시에서 데이터를 반환한 다음, 서버에 데이터를 가져오는 요청을 보내고, 마지막으로 최신 데이터를 제공

    useSWR is a React Hooks library for data fetching that provides a synchronous API.

    When you call an API method, useSWR will automatically orchestrate data fetching and return it to your component. 


    useSWR can fetch data from any source, including APIs, databases, and server-side rendering.
    • Difference
      1. 'useSWR'은 single API endpoint 로부터 데이터를 fetching 하는 것으로 제한된다. 반면, 'React Query' 는 multiple API endpoint들로부터 데이터를 fetch 할 수 있다. =>이러한 점은 React Query가 data fetching 할때 더 다방면으로 만든다.
      2. 'useSWR'은 API endpoint 로부터 가장 최신의 데이터를 return 한다. (최신 데이터를 원할때 유용하지만 경쟁 조건(race condition)을 이끌 수 있음) 'React Query' 는 얼마나 자주 데이터를 API endpoint로부터 fetch되는지 컨트롤 하기 원하는 built-in caching mechanism을 가진다. (이것은 data를  fetch 할때 더 신뢰성 있음) 
      3. 'useSWR'은 errors를 handle 할 수 있는 방법이 없지만, 'React Query'는 error-handling 시스템이 있음.
      4. 'useSWR'은 react hooks로 명쾌하게 디자인 되었지만, 'React Query'는 react hooks와 전통적인 class 방식으로 짜여진 컴포넌트와 호환 가능
      5. 'useSWR'은 fetch 방식으로 , 'React Query'는 Axios로 짜여진 라이브러리
      6. 'useSWR'은 원격 데이터 소스를 query 하도록 허용되지만, 'React Query'는 your aplication's API로부터 데이터를 caching | fetching 하도록 초점을 맞춤 
      7. 'useSWR'은 변화에 의존해서 자동적으로 data를 refetch 하지만, 'React Query'는 얼마나 자주 data를 refetch 했을때와 decide 한 것에 대해서 변화를 일으킴
      8. 'useSWR'은 첫번째 요청이 완료 되기 전까지 초기화 되지 않은 값을 return 하지만, 'React Query'는 만약 그것이 존재한다면 즉각적으로 캐시된 값을 return 한다

    React Query 사용법 (SWR 사용법)

    import { QueryClient, QueryClientProvider, useQuery } from "react-query";
    
    const queryClient = new QueryClient();
    const url = "https://61b88c9d64e4a10017d19053.mockapi.io/user";
    
    const App = () => (
      <div>
        <QueryClientProvider client={queryClient}>
          <ReactQueryProfile />
        </QueryClientProvider>
      </div>
    );
    
    const ReactQueryProfile = () => {
      const {isLoading, error, data, isFetching} = useQuery("users", () =>
        fetch("https://61b88c9d64e4a10017d19053.mockapi.io/user").then(res => res.json())
      );
    
      if (error) return <div>failed to load</div>;
      if (isLoading) return <div>loading...</div>;
    
      return <Profile library="React Query" data={data} />;
    }
    
    const Profile = ({library, data}) => (
      <div>
        <h1>Users from {library}</h1>
        {data.map(user => <p>{user.level} developer <strong>{user.name}</strong></p>)}
      </div>
    )
    
    export default App;

    Provider

    SWR은 별도의 Provider 없이 컴포넌트에서 바로 사용가능하지만, React Query 경우 Provider로 감싸지 않을 경우 에러

    Fetcher

    'useSWR'은 첫번째 인자에 두번째 인자 fetcher에서 사용할 url (key)이 위치하지만 (전역 설정으로 생략 가능)

    'useQeury'는 두번째 인자 fetcher에 url을 직접 전달(항상)

    Status

    'useSWR'은 isVaildating 으로 상태 표현,

    'useQuery'은 isLoading, isFetching 을 통해 데이터 상태 표현 (isFetching은 첫 로드를 제외한 데이터 업데이트 시 상태값)

    Mutation

    'useSWR'의 Mutate는 useSWR을 통해 받아온 data를 CSR에서 변형시켜 업데이트

    'React Query '의 Mutation은 useMutaion 으로 "POST" | "GET" | "PUT" | "DELETE" 를 통해 서버의 상태를 변형

    const mutation = useMutation(newTodo => {
         return axios.post('/todos', newTodo)
       })

     

    참고: https://tech.madup.com/react-query-vs-swr/

    https://codedamn.com/news/javascript/useswr-vs-react-query-differences-and-which-one-should-you-choose

Designed by Tistory.