Jotai: Claude Code 활용 가이드
jotai: Claude Code 활용. 실용적인 팁과 코드 예시를 포함합니다.
Jotaiでボトムアップの状態관리を実現する
Jotaiは「アトム」と呼ばれる最小単位で状態を관리するReact向け라이브러리です。Recoilに似たアプローチですが、よりシンプルなAPIとTypeScriptファーストの설계が特徴です。Claude Code는 アトム설계から複雑な派生状態の구축まで的確に생성します。
기본적인アトムの설계
Claude Code에アトムの구성を依頼합시다。
> Jotaiでダークモード대응の테마관리を作って。
> システム설정の検出、永続化、컴포넌트からの전환に대응して。
import { atom, useAtom, useAtomValue, useSetAtom } from "jotai";
import { atomWithStorage } from "jotai/utils";
type Theme = "light" | "dark" | "system";
// localStorage に永続化されるアトム
const themePreferenceAtom = atomWithStorage<Theme>("theme", "system");
// システムのダークモード설정を検出する読み取り専用アトム
const systemDarkModeAtom = atom<boolean>((get) => {
if (typeof window === "undefined") return false;
return window.matchMedia("(prefers-color-scheme: dark)").matches;
});
// 실제로適用される테마を計算する派生アトム
const resolvedThemeAtom = atom<"light" | "dark">((get) => {
const preference = get(themePreferenceAtom);
if (preference === "system") {
return get(systemDarkModeAtom) ? "dark" : "light";
}
return preference;
});
// カスタムフック
export function useTheme() {
const [preference, setPreference] = useAtom(themePreferenceAtom);
const resolvedTheme = useAtomValue(resolvedThemeAtom);
return {
preference,
resolvedTheme,
setTheme: setPreference,
isDark: resolvedTheme === "dark",
};
}
派生アトムで複雑な状態を구성
アトムを組み合わせて複雑な状態を表現するパターンです。
// 基本アトム
const todosAtom = atom<Todo[]>([]);
const filterAtom = atom<"all" | "active" | "completed">("all");
const searchQueryAtom = atom("");
// 派生アトム: フィルタリングされたTodo
const filteredTodosAtom = atom((get) => {
const todos = get(todosAtom);
const filter = get(filterAtom);
const query = get(searchQueryAtom).toLowerCase();
let result = todos;
// フィルタ適用
switch (filter) {
case "active":
result = result.filter((t) => !t.completed);
break;
case "completed":
result = result.filter((t) => t.completed);
break;
}
// 검색適用
if (query) {
result = result.filter((t) => t.title.toLowerCase().includes(query));
}
return result;
});
// 統計情報の派生アトム
const todoStatsAtom = atom((get) => {
const todos = get(todosAtom);
return {
total: todos.length,
active: todos.filter((t) => !t.completed).length,
completed: todos.filter((t) => t.completed).length,
completionRate: todos.length
? Math.round(
(todos.filter((t) => t.completed).length / todos.length) * 100
)
: 0,
};
});
비동기アトムで데이터취득
Jotaiの비동기アトムを使って서버から데이터を취득するパターンです。
import { atom } from "jotai";
import { atomWithQuery } from "jotai-tanstack-query";
// 비동기のread-writeアトム
const currentUserAtom = atom<User | null>(null);
const fetchUserAtom = atom(
(get) => get(currentUserAtom),
async (_get, set) => {
const response = await fetch("/api/me");
const user = await response.json();
set(currentUserAtom, user);
}
);
// TanStack Queryとの연동
const userQueryAtom = atomWithQuery((get) => ({
queryKey: ["user", get(userIdAtom)],
queryFn: async ({ queryKey: [, userId] }) => {
const res = await fetch(`/api/users/${userId}`);
return res.json();
},
enabled: !!get(userIdAtom),
}));
アトムファミリーで動的なアトム생성
アイテムごとに独立したアトムを動的に생성するパターンです。
import { atom } from "jotai";
import { atomFamily } from "jotai/utils";
// IDごとに独立したアトムを생성
const todoAtomFamily = atomFamily((id: string) =>
atom<Todo>({
id,
title: "",
completed: false,
createdAt: new Date(),
})
);
// ID리스트を관리するアトム
const todoIdsAtom = atom<string[]>([]);
// Usage example
function TodoItem({ id }: { id: string }) {
const [todo, setTodo] = useAtom(todoAtomFamily(id));
const toggleComplete = () => {
setTodo((prev) => ({ ...prev, completed: !prev.completed }));
};
return (
<div>
<input
type="checkbox"
checked={todo.completed}
onChange={toggleComplete}
/>
<span>{todo.title}</span>
</div>
);
}
function TodoList() {
const ids = useAtomValue(todoIdsAtom);
return (
<div>
{ids.map((id) => (
<TodoItem key={id} id={id} />
))}
</div>
);
}
Zustandとの使い分け
JotaiとZustandはどちらもReactの状態관리라이브러리ですが、アプローチが異なります。
- Jotai - ボトムアップ。小さなアトムを組み合わせて状態を구축。컴포넌트に密結合な状態に向く
- Zustand - トップダウン。ストア単位で状態を설계。グローバルなビジネスロジックに向く
両者を組み合わせることも가능합니다。UIの局所的な状態はJotai、앱全体の状態はZustandという使い分けが効果的です。
정리
Jotaiのアトミックなアプローチは、컴포넌트単位での状態관리に優れています。Claude Codeを활용すれば、アトム설계から派生状態の구축、비동기処理まで빠르게구현할 수 있습니다。
ストア타입の状態관리はZustand状態관리가이드を、Reactでの개발全般はReact개발を爆速にする方法를 참고하세요.Jotai공식 문서も併せて확인합시다。
무료 PDF: 5분 완성 Claude Code 치트시트
이메일 주소만 등록하시면 A4 한 장짜리 치트시트 PDF를 즉시 보내드립니다.
개인정보는 엄격하게 관리하며 스팸은 보내지 않습니다.
이 글을 작성한 사람
Masa
Claude Code를 적극 활용하는 엔지니어. 10개 언어, 2,000페이지 이상의 테크 미디어 claudecode-lab.com을 운영 중.
관련 글
Claude Code 다국어 글을 매일 발행하기 전에 확인할 7가지
누락된 언어, 깨진 CTA, 반영되지 않은 배포를 막기 위해 다국어 Claude Code 글을 매일 발행하기 전에 확인할 체크리스트입니다.
Codex Automations란? 잠자는 동안 AI가 콘텐츠 운영을 처리하게 하는 방법
Codex Automations로 트래픽 분석, 주제 선정, 글 작성, CTA 개선, 배포까지 자동화하는 실전 가이드.
Claude Code × GCP Cloud Functions 완전 가이드 | 서버리스 함수 초고속 개발
Claude Code로 GCP Cloud Functions를 효율화. HTTP/Pub/Sub/Firestore 트리거 구현부터 로컬 테스트·배포 자동화까지, Masa의 실무 경험을 토대로 실제 코드로 해설.