jotai 와 zustand, redux 등등 스토어들의 상태관리 멘탈모델을 비교해보자

1. jotai & recoil 과 같은 원자단위 상태

// 기본 상태 atoms
const priceAtom = atom(100);              // 가격
const quantityAtom = atom(2);             // 수량
const taxRateAtom = atom(0.1);            // 세율

// 의존성이 있는 파생 상태
const subtotalAtom = atom(                // 소계
  (get) => get(priceAtom) * get(quantityAtom)
);

const taxAtom = atom(                     // 세금
  (get) => get(subtotalAtom) * get(taxRateAtom)
);

const totalAtom = atom(                   // 총액
  (get) => get(subtotalAtom) + get(taxAtom)
);

그런데 만약 이걸 리덕스로 구현한다면, 리듀서로 개선하거나 selector 로 계산해주어야함
즉, jotai 는 의존성이 명시적임 (get함수를 사용하여 각 atom 들이 어떤 atom 을 참조하는지 바로 알 수 있음)

atom 들은 무엇으로 구분되는가?

2. redux, zustand 와 같은 단일스토어 상태

리덕스의 경우 액션, 리듀서를 각각 정의하고 그걸 스토어에 등록해야한다.

// 1. Action 정의
const INCREMENT = 'INCREMENT';
const addTodo = (text) => ({ 
  type: 'ADD_TODO', 
  payload: text 
});

// 2. Reducer - 순수 함수
const reducer = (state = initialState, action) => {
  switch (action.type) {
    case INCREMENT:
      return { ...state, count: state.count + 1 };
    case 'ADD_TODO':
      return { 
        ...state, 
        todos: [...state.todos, action.payload] 
      };
    default:
      return state;
  }
};

// 3. Store 생성
const store = createStore(reducer);

// 4. 사용
const Component = () => {
  const count = useSelector(state => state.count);
  const dispatch = useDispatch();

  return (
    <button onClick={() => dispatch({ type: INCREMENT })}>
      {count}
    </button>
  );
};
// 1. Store 생성 - 상태와 액션을 한번에 정의
const useStore = create((set) => ({
  count: 0,
  todos: [],
  increment: () => set((state) => ({ 
    count: state.count + 1 
  })),
  addTodo: (text) => set((state) => ({
    todos: [...state.todos, text]
  }))
}));

// 2. 사용
const Component = () => {
  const count = useStore((state) => state.count);
  const increment = useStore((state) => state.increment);

  return (
    <button onClick={increment}>
      {count}
    </button>
  );
};

트리기반이 왜 필요할까?

1차원적으로 봤을 때, 굳이 아톰단위로 나눠도 될 상태를 트리기반으로 나눠서 중앙에서 관리해야하는 이유가 뭘까? 아톰기반 상태관리 툴에 비해 트리기반 상태관리 툴의 이점은 뭘까?