react query 프로젝트에 적용하기

boyeonJ·2023년 12월 12일
1

React

목록 보기
27/30
post-thumbnail
post-custom-banner

How

install

npm i react-query

queryClient생성 후 QueryClientProvider로 감싸기

import "./App.css";
import Products from "./pages/Products";
import {
  QueryClient,
  QueryClientProvider,
} from 'react-query'


function App() {
  const queryClient = new QueryClient()

  return  <QueryClientProvider client={queryClient}><Products /></QueryClientProvider>;
}

export default App;

Component에서 사용하기

기존 useEffect와 단순 await, async와 비교해봅시다!

1. get: useQuery

const Products = () => {
  const [products, setProducts] = useState<Product[]>([]);

  const query = useQuery('products', getProduct);
  console.log(query);
  
  //기존 코드
  // const fetchPosts = async () => {
  //   const res: AxiosRequestConfig<{ products: Product[] }> = await getProduct();

  //   setProducts(res?.data?.products ?? []);
  // };

  // useEffect(() => {
  //   fetchPosts();
  // }, []);

Devtools 사용하기

App.tsx에 ReactQueryDevtools을 import해주어 사용합니다.

import "./App.css";
import Products from "./pages/Products";
import { QueryClient, QueryClientProvider } from "react-query";
import { ReactQueryDevtools } from 'react-query/devtools'

function App() {
  const queryClient = new QueryClient();

  return (
    <QueryClientProvider client={queryClient}>
      <ReactQueryDevtools initialIsOpen={false} />
      <Products />
    </QueryClientProvider>
  );
}

export default App;

post-custom-banner

0개의 댓글