要点だけ端的に説明します。
インストール
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;
値を入力して出力するだけです。
サンプルコードを置いておくのでもしよかったら確認してください。
https://github.com/H-goto16/jotai-test