<--SyntaxHighlighter--> SyntaxHighlighter.all();

 

1. Library 설치

yarn add react-query

 

2. 프로젝트 구조

 

/src

    ㄴcomponents

        * RQ1 (테스트용)

        * RQ2 (실 사용 컴포넌트)

    ㄴcustomHooks

        * useUsers.js

    *App.js

    *index.js

 

 

 

 

 

 

 

 

 

 

3. 코드

(1) App.js

import { QueryClient, QueryClientProvider } from "react-query";
import RQ2 from "./components/RQ2";

const queryClient = new QueryClient();

function App() {
  return (
    <div className="App">
      <QueryClientProvider client={queryClient}>
        <RQ2 />
      </QueryClientProvider>
    </div>
  );
}

export default App;

 

(2) src/customHooks/useUsers.js

import { useQuery } from "react-query";
import axios from "axios";

const fetchUsers = async () => {
  const { data } = await axios.get(
    `https://jsonplaceholder.typicode.com/users`
  );
  return data;
};

export default () => {
  const { status, data, error } = useQuery("users", fetchUsers);
  return { status, data, error };
};

(3) src/components/RQ2.jsx

import React from "react";
import useUsers from "../customHooks/useUsers";

const RQ1 = () => {
  const { data } = useUsers();

  return (
    <section>
      <h1>사용자 목록</h1>
      {data && (
        <ul>
          {data.map((user) => {
            return (
              <li key={user.id}>
                {user.username} ({user.email})
              </li>
            );
          })}
        </ul>
      )}
    </section>
  );
};

export default RQ1;

+ Recent posts