오늘은 React Query 에 대해 설명해보려고 합니다 !!

              리액트 쿼리를 처음 들은 나.

          리액트 쿼리를 처음 들은 나.

리액트 쿼리란 ❓

<aside> <img src="https://noticon-static.tammolo.com/dgggcrkxq/image/upload/v1668404990/noticon/vvlwk62hghkmolj6swij.png" alt="https://noticon-static.tammolo.com/dgggcrkxq/image/upload/v1668404990/noticon/vvlwk62hghkmolj6swij.png" width="40px" />

fetching, caching, 서버 데이터와의 동기화를 지원해주는 라이브러리

</aside>

✅ if(kakao)2021 - 카카오페이 프론트엔드 개발자들이 React Query를 선택한 이유」 세줄요약

  1. React Query는 React Application에서 서버 상태를 불러오고, 캐싱하며, 지속적으로 동기화하고 업데이트하는 작업을 도와주는 라이브러리입니다.

  2. 복잡하고 장황한 코드가 필요한 다른 데이터 불러오기 방식과 달리 React Component 내부에서 간단하고 직관적으로 API를 사용할 수 있습니다.

  3. 더 나아가 React Query에서 제공하는 캐싱, Window Focus Refetching 등 다양한 기능을 활용하여 API 요청과 관련된 번잡한 작업 없이 “핵심 로직”에 집중할 수 있습니다.

→ 서버에서 데이터를 비동기적으로 가져올 때, 데이터 로딩, 캐싱, 리패칭 등을 쉽게 처리할 수 있게 해준다는 것인데 … 어떻게 ?

useQueryuseMutation을 사용해서 !

우선 리액트 쿼리의 useQuery 훅에서 자동으로 처리되는 요소들에 대해 알아보도록 하겠습니다 !

로딩 (Loading) ⚫⚪⚪⚪

<aside> <img src="https://noticon-static.tammolo.com/dgggcrkxq/image/upload/v1711609978/noticon/goy8tfeuevcdimme8vcl.png" alt="https://noticon-static.tammolo.com/dgggcrkxq/image/upload/v1711609978/noticon/goy8tfeuevcdimme8vcl.png" width="40px" />

서버에서 데이터를 가져오는 동안 데이터가 준비되지 않은 상태를 말합니다.

리액트 쿼리는

isLoading

상태를 통해 로딩 중인지 쉽게 알 수 있습니다.

</aside>

import React from 'react';
import { useQuery } from 'react-query';

const fetchData = async () => {
  const response = await fetch('<https://jsonplaceholder.typicode.com/posts>');
  return response.json();
};

const LoadingExample = () => {
  const { data, isLoading } = useQuery('posts', fetchData);

  if (isLoading) {
    return <p>Loading...</p>; // 로딩 중일 때 표시
  }

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

export default LoadingExample;