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

1. Library 설치

yarn add recoil

 

2. 구성

 

/src

    ㄴ components

        * UserList.jsx

    ㄴ recoil

        * state.js

    *App.js

    *Index.js

 

 

 

 

 

 

 

 

 

 

3. 코드

(1) src/App.js

import React, { ErrorBoundary } from "react";
import { RecoilRoot } from "recoil";
import UserList from "./components/UserList";

function App() {
  return (
    <div className="App">
      <RecoilRoot>
        <React.Suspense fallback={<div>로딩중...</div>}>
          <UserList />
        </React.Suspense>
      </RecoilRoot>
    </div>
  );
}

export default App;

(2) src/recoil/state.js

import { atom, selector } from "recoil";

export const userListState = atom({
  key: "userListState",
  default: [],
});

export const currentUserListQuery = selector({
  key: "currentUserListQuery",
  get: async ({ get }) => {
    get(userListState);

    const response = await fetch("https://jsonplaceholder.typicode.com/users");
    return await response.json();
  },
});

(3) src/components/UserList.jsx

App.js에서 React.Suspense를 사용할 경우 useRecoilValue를 사용할 수 있습니다. Suspense를 사용하지 않을 경우엔

비동기 전용 Hook인 useRecoilValueLoadable을 사용합니다.

import React from "react";
import { useRecoilValueLoadable, useRecoilValue } from "recoil";
import { currentUserListQuery } from "../recoil/state";

export default function UserList() {
  const users = useRecoilValue(currentUserListQuery);

  return (
    <ul>
      {users.map((user) => {
        return (
          <li key={user.id}>
            {user.username} · {user.email}
          </li>
        );
      })}
    </ul>
  );
}

+ Recent posts