1
0

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.

状態管理ライブラリ Jotai の使い方

Posted at

要点だけ端的に説明します。

インストール

yarn add jotai

stateの宣言

state管理するにはatom()関数を呼び出します。
型はatom<string>(initialValue: string)となります。

atomWithStorageはlocalStorageを使用して保存します。そのため、ブラウザがリロードしても前の値の状態を保ちます。

型はatomWithStorage<string>(key: string, initialValue: string)です。keyはlocalStorageに保存されるKeyの名前になります。

src/jotai/state.ts
import { atom } from "jotai";
import { atomWithStorage } from "jotai/utils";

export const state = atom<string>("");
export const stateWithStorage = atomWithStorage("storageKey", "");

保存と呼び出し

あとはuseStateのように使用できます。
厳密には誤りがあると思いますが、以下のように考えてもらえれば大丈夫です。

const [呼び出し名, 保存関数] = useAtom(state名);

よってサンプルコードは以下のようになります。

src/pages/index.tsx
import { state, stateWithStorage } from "@/jotai/state";
import { useAtom } from "jotai";

const Home = () => {
  const [exampleState, setExampleState] = useAtom(state);
  const [storageState, setStorageState] = useAtom(stateWithStorage);

  return <>Hello World</>;
};

export default Home;

保存と呼び出しは以下のようになります。

保存

setExampleState("value");
setStorageState("value"); // localStorageに保存される

呼び出し(例)

console.log(exampleState, storageState);

サンプルコード :

src/pages/index.tsx
import { state, stateWithStorage } from "@/jotai/state";
import { useAtom } from "jotai";

const Home = () => {
  const [exampleState, setExampleState] = useAtom(state);
  const [storageState, setStorageState] = useAtom(stateWithStorage);

  return (
      <center className="mt-[30vh] text-3xl">
        <h1>Jotai Testing</h1>
        <div>
          <p>Example state: {exampleState}</p>
          <input
            className="border"
            type="text"
            onChange={(e) => setExampleState(e.target.value)}
          />
          <p>Storage state: {storageState}</p>
          <input
            className="border"
            type="text"
            onChange={(e) => setStorageState(e.target.value)}
          />
        </div>
      </center>
  );
};

export default Home;

値を入力して出力するだけです。

jotai.gif

サンプルコードを置いておくのでもしよかったら確認してください。
https://github.com/H-goto16/jotai-test

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?