Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

jotai

БесплатноБез исполняемых скриптовНе проверен

Jotai is a small state management library for React built on atoms: pieces of state that components subscribe to individually, so only the components reading…

TerminalSkillsот TerminalSkills★ 221 звезда на GitHub

Об этом скилле

Jotai — Atomic State Management for React

Overview

Jotai (current release 3.0.1) keeps state in small atoms. An atom config is just a definition; the value lives in a store. Components read atoms through hooks and re-render only when those atoms change. No Provider is needed for global state (the default store is used), and there are no reducers or actions.

Jotai v3 keeps the public hooks API of v2 but is ESM-only and requires React 18+, TypeScript 5.5+ and Node.js >=22.12. It removed atomFamily from jotai/utils (now the separate jotai-family package), loadable (use unwrap), jotai/babel (now jotai-babel), the setSelf read option and the delay hook option.

Instructions

Install

npm install jotai
npm install jotai-family   # only if you use atomFamily

Atoms and hooks

import { Suspense } from "react";
import { atom, useAtom, useAtomValue, useSetAtom } from "jotai";
import { atomWithStorage } from "jotai/utils";

const countAtom = atom(0);                                  // primitive
const doubledAtom = atom((get) => get(countAtom) * 2);      // read-only derived
const darkModeAtom = atomWithStorage("darkMode", false);    // localStorage

const userIdAtom = atom(1);
const userAtom = atom(async (get) => {                      // async derived
  const res = await fetch(`/api/users/${get(userIdAtom)}`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return (await res.json()) as { name: string; email: string };
});

function Counter() {
  const [count, setCount] = useAtom(countAtom);
  const doubled = useAtomValue(doubledAtom);                // read-only hook
  return <button onClick={() => setCount((c) => c + 1)}>{count} x 2 = {doubled}</button>;
}

function UserProfile() {
  const user = useAtomValue(userAtom);                      // suspends until resolved
  return <p>{user.name} ({user.email})</p>;
}

export function App() {
  return (
    <Suspense fallback={<p>Loading user...</p>}>
      <Counter />
      <UserProfile />
    </Suspense>
  );
}

Hook choice: useAtom for read and write, useAtomValue for read only, useSetAtom for write only (the component does not re-render when the value changes).

Writable derived and write-only atoms

const nameAtom = atom("Alice");
const upperNameAtom = atom(
  (get) => get(nameAtom).toUpperCase(),
  (_get, set, newName: string) => set(nameAtom, newName),
);

type Product = { id: string; title: string; price: number };
type CartItem = Product & { qty: number };

const cartItemsAtom = atom<CartItem[]>([]);
const cartTotalAtom = atom((get) =>
  get(cartItemsAtom).reduce((sum, i) => sum + i.price * i.qty, 0),
);
const addToCartAtom = atom(null, (get, set, product: Product) => {   // write-only: first arg null
  const items = get(cartItemsAtom);
  const existing = items.find((i) => i.id === product.id);
  set(
    cartItemsAtom,
    existing
      ? items.map((i) => (i.id === product.id ? { ...i, qty: i.qty + 1 } : i))
      : [...items, { ...product, qty: 1 }],
  );
});

Atom families (v3: separate package)

import { atom } from "jotai";
import { atomFamily } from "jotai-family";   // v2 only: import from "jotai/utils"

const todoAtomFamily = atomFamily((id: string) =>
  atom(async () => (await fetch(`/api/todos/${id}`)).json()),
);
const todoAtom = todoAtomFamily("42");        // same param returns the cached atom
todoAtomFamily.remove("42");                  // free a param you no longer need

Persisting with atomWithStorage

atomWithStorage(key, initialValue, storage?, { getOnInit }) uses localStorage and JSON by default and syncs across tabs. In a client-only app, pass { getOnInit: true } as the fourth argument if the stored value must be read on first render; otherwise the first render shows initialValue. Set an atom to RESET (from jotai/utils) to delete the key. For sessionStorage or server rendering, build the storage with createJSONStorage(() => typeof window !== "undefined" ? window.sessionStorage : undefined).

Provider and stores

A <Provider> gives a subtree its own store; use it for tests, isolation, or per-request state in SSR. To read or write outside React, const store = createStore(); store.get(countAtom); store.set(countAtom, 5); and pass <Provider store={store}>.

Examples

Example 1: "Replace prop drilling for a theme toggle that survives reloads"

import { useAtom } from "jotai";
import { atomWithStorage } from "jotai/utils";

export const themeAtom = atomWithStorage<"light" | "dark">("theme", "light", undefined, { getOnInit: true });

export function ThemeToggle() {
  const [theme, setTheme] = useAtom(themeAtom);
  return <button onClick={() => setTheme(theme === "dark" ? "light" : "dark")}>Theme: {theme}</button>;
}

Any component can import themeAtom; the choice is stored under the theme key and is shared between tabs.

Example 2: "Add to cart button that does not re-render on every cart c

Полный SKILL.md на GitHub

Установить jotai в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

_scores.json

FAQ

Что делает скилл jotai?

Jotai is a small state management library for React built on atoms: pieces of state that components subscribe to individually, so only the components reading a changed atom re-render. Use it when asked to add Jotai, replace useState prop drilling or Context, build derived or async state with atoms, persist a preference with atomWithStorage, or migrate Jotai v2 to v3.

Как установить скилл jotai?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл jotai запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить jotai с