LoginSignup
5
0

More than 3 years have passed since last update.

Rcoilつかってみたったった

Last updated at Posted at 2020-11-24

はじめに

ReactとReduxを勉強し始めて3ヶ月ほどの私ですが

Redux以外の状態管理ライブラリーを使ってみたい!!

とのことで今回Recoilを学習してみました

Recoilとは

Recoil.png

faceBookさんが作ったReactの状態管理ライブラリー。その名の通り真ん中にコイルみたいなのあるね

さっそく使ってみよう

Atoms

index.js
import { atom } from "recoil";

export const textState = atom({
  key: "textState",
  default: "",
});

atomsは一意とkeyとdefaultのStateを設定する

その名の通りdefaultはReactのHooksのuseStateの初期値みたいな感じです

このatomのStateにdataが入ってきます

App.jsx
import { RecoilRoot } from "recoil";
import Router from "./Router";

const App = () => {
  return (
    <RecoilRoot>
      <Router /> 
    </RecoilRoot>
  );
};

atomsのStateはRecoilRootでラップしたコンポーネントは参照できます

selector

selector.js
import { selector } from "recoil";
import { textState } from "../index";

export const textCountState = selector({
  key: "textCountState",
  get: ({ get }) => {
    const text = get(textState);

    return text.length;
  },
});

atomsのstate(textState)を受け取って別の処理をした値を返すことができる

selector.js
import { selector } from "recoil";
import { userNamesList } from "../index";
import api from "../../../services/api";

export const userToFollowerMap = selector({
  key: "userToFollowerMap",
  get: async ({ get }) => {
    const _userNamesList = get(userNamesList);

    const responses = await Promise.all(
      _userNamesList.map((userName) => api.get(`/users/${userName}`))
    );
    const followerMap = {};
    responses.forEach((response) => {
      const { data: user } = response;

      followerMap[user.login] = user.followers;
    });
    return followerMap;
  },
});

こんな感じに非同期処理のQueryとしてStateを受けとり、取得した値を返すこともできる

ではComponentごとにatomsやselectorのStateを追加したり参照する方法

useRecoilState

Textinpu.jsx
import React from "react";
import { useRecoilState } from "recoil";
import { textState } from "../atoms/text/index";

const TextInput = () => {
  const [text, setText] = useRecoilState(textState);

  const onChange = (e) => {
    setText(e.target.value);
  };

  return (
    <div>
      <input type="text" value={text} onChange={onChange} />
      <br />
      Echo:{text}
    </div>
  );
};

ReactのHoosのグローバルState版みたいな感じに使える

textで値を参照できて,setTextでatomsに値を追加できるuseRecoilStateにはatomsのStateを渡す

useSetRecoilState

Textinput.jsx
  const setText = useSetRecoilState(textState);

useRecoilStateのatomsに追加できるだけ版setTextで追加できます。

参照もするのであればuseRecoilStateをつかえばいいかな

useRecoilValue

textLengthCount.jsx
import { useRecoilValue } from "recoil";
import { textCountState } from "../atoms/text/selectors/charCount";

const  textLengthCount = () => {
  const count = useRecoilValue(textCountState);

  return <div>text length Count: {count}</div>;
};

逆に参照だけできる版

atomsやSelectorの値をComponenごとで参照できる

まとめ

Reduxより簡単にかける反面atoms内のオブジェクトに再代入しようとしたらReadOnlyですっておこられた

もうちょっと使ってみてReduxとRecoil両方つかって挙あげれるようになりたい

5
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
0