0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Recoil の公式チュートリアルやってみた

0
Last updated at Posted at 2023-11-26

初めに

最近業務でわからんコードがあり、勉強しました
少し、使った技術等は公式とは変えましたが、環境的には問題ないっぽいんで悪しからず
また、全てのコンポーネント等はApp.tsxに記述していくそうです(公式ドキュメントでは)

※ App.cssとindex.cssの中身は削除してます

Recoilとは

Metaによって開発されたグローバル状態管理ライブラリ

まず、プロジェクトの立ち上げ

$ yarn create vite
? Project name: practice3
? Select a framework: React
? Select a variant: TypeScript + SWC
$ cd practice3
$ yarn
$ yarn add recoil

ReactRootの作成

RecoilでStateをグローバルに管理するには、状態管理したいコンポーネントの最上位コンポーネントに<ReactRoot>を書いておく必要がある

// App.tsx
import React from "react";
import { RecoilRoot, atom, selector, useRecoilState, useRecoilValue } from "recoil";

function App() {
    return (
        <RecoilRoot>
            <CharactorCounter />
        </RecoilRoot>
    );
}

export default App;

Atomの作成

atomはアプリケーションの一部のStateを管理する。
ここで管理されるStateはアプリケーション全体で共有され、更新、取得が行われたコンポーネントのみ再レンダリングされる。

key: 他のatom、のちに紹介するselectorと区別させるための一意なID。
default: 初期値、またはデフォルト値

// App.tsx
const textState = atom({
    key: "textState",
    default: "",
});

CharactorCounterコンポーネントの実装

// App.tsx
function CharactorCounter() {
    return (
        <div>
            <TextInput />
            <CharactorCount />
        </div>
    );
}

Selectorの作成

Selectorとはatomで管理しているStateの値を何らかの形に加工して、返すもの。
今回で言うと、先ほど作成したtextStateというatomで管理している値の長さを返している。

// App.tsx
const charCountState = selector({
    key: "charCountState",
    get: ({ get }) => {
        const text = get(textState);
        return text.length;
    },
});

CharactorCountコンポーネントの作成

上で作成した、Selector charCountState を使って、入力した文字列の長さを表示させます。
selectorで返されている値はuseRecoilValue(selector名)で取得できます

// App.tsx
function CharacterCount() {
    const count = useRecoilValue(charCountState);
    return <>Character Count: {count}</>;
}

デモ!!

qiita_recoil_tutorial.gif

終わりに

どうでしたでしょうか。
今回は以下の公式ドキュメントのGetting Startedをそのまま行ってみました。
誰かの参考程度になったら嬉しいです。

全然関係ないんですが、毎年季節の変わり目には必ず風邪をひいている私ですが、今年からマルチビタミンを積極的に摂取し始めているからか、風邪ひかなくなって逆に怖い今日この頃です。
みなさんも体調にはお気をつけて。。

参考

https://recoiljs.org/docs/introduction/getting-started/

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?