React Query - 시작하기

목차

참고

의존성 추가

$ npm i @tanstack/react-query
# or
$ yarn add @tanstack/react-query

Provider

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App.tsx";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";

const queryClient = new QueryClient();

ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
</React.StrictMode>
);

useQuery

import React from "react";
import axios from "axios";
import { useQuery } from "@tanstack/react-query";

const App = () => {
const { isLoading, error, data } = useQuery({
queryKey: ["repoData"],
queryFn: () =>
axios
.get("https://api.github.com/repos/TanStack/query")
.then((res) => res.data),
});

if (isLoading) return "Loading...";
if (error) return "An error has occurred: " + error.message;

return (
<div>
<h1>{data.name}</h1>
<p>{data.description}</p>
<strong>👀 {data.subscribers_count}</strong>{" "}
<strong>✨ {data.stargazers_count}</strong>{" "}
<strong>🍴 {data.forks_count}</strong>
</div>
);
};

export default App;
Share