๐ŸŒ Web Development

Jotai

Jotai (Japanese for 'state')

Jotai is an atom-based state management library for React. Inspired by Recoil, it is designed with a simpler API and smaller bundle size, and enables fine-grained state management without boilerplate.

๐Ÿ“– Detailed Explanation

Jotai means 'state' in Japanese and is a React state management library developed by Daishi Kato in 2021. It was inspired by Recoil's atomic approach, but offers a smaller bundle size (about 3KB gzip) and a simplified API. It works without a Provider and natively supports React Suspense and Concurrent Mode.

The core concept of Jotai is the 'atom'. An atom is the smallest unit of state, is defined outside of components, and can be shared among multiple components. Because each atom is subscribed to independently, when a specific atom changes, only the components subscribed to that atom are re-rendered. This prevents unnecessary re-renders and optimizes performance.

Derived state is created by combining other atoms using the get parameter in an atom function. Async atoms can be defined using an async function and integrate naturally with React Suspense. Through various utility atoms such as atomWithStorage and atomWithObservable, it provides extended features such as localStorage integration and RxJS integration.

Jotai is maintained by the poimandres team together with Zustand, and is one of the most popular lightweight state management libraries in the React ecosystem. It fully supports TypeScript and also provides a devtools extension. It is particularly suitable when fine-grained, component-level state management is needed, or when you want to solve the unnecessary re-rendering problem of the Context API.

๐Ÿ’ป Code Example

import { atom, useAtom, useAtomValue, useSetAtom } from 'jotai';
import { atomWithStorage } from 'jotai/utils';

// 1. ๊ธฐ๋ณธ atom ์ •์˜ (์ปดํฌ๋„ŒํŠธ ์™ธ๋ถ€์—์„œ)
const countAtom = atom(0);
const nameAtom = atom('');

// 2. ํŒŒ์ƒ atom (๋‹ค๋ฅธ atom ๊ธฐ๋ฐ˜ ๊ณ„์‚ฐ)
const doubleCountAtom = atom((get) => get(countAtom) * 2);

// 3. ์ฝ๊ธฐ/์“ฐ๊ธฐ atom (์ปค์Šคํ…€ ๋กœ์ง)
const countWithLimitAtom = atom(
  (get) => get(countAtom),
  (get, set, newValue: number) => {
    // 0-100 ์‚ฌ์ด๋กœ ์ œํ•œ
    const clampedValue = Math.max(0, Math.min(100, newValue));
    set(countAtom, clampedValue);
  }
);

// 4. ๋น„๋™๊ธฐ atom (๋ฐ์ดํ„ฐ ํŽ˜์นญ)
const userAtom = atom(async (get) => {
  const response = await fetch('/api/user');
  return response.json();
});

// 5. localStorage ์—ฐ๋™ atom
const themeAtom = atomWithStorage<'light' | 'dark'>('theme', 'light');

// 6. ์ปดํฌ๋„ŒํŠธ์—์„œ ์‚ฌ์šฉ
function Counter() {
  // ์ฝ๊ธฐ + ์“ฐ๊ธฐ
  const [count, setCount] = useAtom(countAtom);

  // ์ฝ๊ธฐ๋งŒ (๋ฆฌ๋ Œ๋”๋ง ์ตœ์ ํ™”)
  const doubleCount = useAtomValue(doubleCountAtom);

  // ์“ฐ๊ธฐ๋งŒ (๋ฆฌ๋ Œ๋”๋ง ์ตœ์ ํ™”)
  const setName = useSetAtom(nameAtom);

  return (
    <div>
      <p>Count: {count}</p>
      <p>Double: {doubleCount}</p>
      <button onClick={() => setCount(c => c + 1)}>
        Increment
      </button>
      <button onClick={() => setName('Alice')}>
        Set Name
      </button>
    </div>
  );
}

// 7. Suspense์™€ ํ•จ๊ป˜ ๋น„๋™๊ธฐ atom ์‚ฌ์šฉ
function UserProfile() {
  const user = useAtomValue(userAtom); // ์ž๋™์œผ๋กœ Suspense ํŠธ๋ฆฌ๊ฑฐ

  return <div>Welcome, {user.name}</div>;
}

function App() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <UserProfile />
    </Suspense>
  );
}

// 8. ์‹ค๋ฌด ํŒจํ„ด: ๊ธฐ๋Šฅ๋ณ„ atom ๋ชจ๋“ˆํ™”
// atoms/cart.ts
export const cartItemsAtom = atom<CartItem[]>([]);

export const cartTotalAtom = atom((get) => {
  const items = get(cartItemsAtom);
  return items.reduce((sum, item) => sum + item.price * item.quantity, 0);
});

export const addToCartAtom = atom(
  null,
  (get, set, item: CartItem) => {
    const items = get(cartItemsAtom);
    const existing = items.find(i => i.id === item.id);

    if (existing) {
      set(cartItemsAtom, items.map(i =>
        i.id === item.id ? { ...i, quantity: i.quantity + 1 } : i
      ));
    } else {
      set(cartItemsAtom, [...items, { ...item, quantity: 1 }]);
    }
  }
);

๐Ÿ—ฃ๏ธ Examples of Practical Conversations

๐Ÿ’ฌ Situation: Discussing which state management library to choose for a new project

Junior "I'm thinking of using Redux for state management, but it seems like there's too much boilerplate. Is there a simpler alternative?"
Senior "It depends on the project size, but if you have a lot of component-level state, I'd recommend Jotai. You just define an atom and use it right away with useAtom. You can get the same result with far less code than Redux Toolkit."
Junior "It seems similar to Recoil. What's the difference?"
Senior "Jotai has a much smaller bundle size (3KB vs 25KB) and works without a Provider. Recoil requires a key string, whereas with Jotai an atom reference alone is enough. Both come from Facebook, but Jotai is more minimal and more actively maintained. Our team uses a combination of Jotai + TanStack Query to separate server state from client state."

โš ๏ธ Cautions

๐Ÿ”— Related Terms

๐Ÿ“š Learn More