React 전역 상태 관리 라이브러리를 결정하던 중 최종적으로 Jotai와 Zustand로 후보가 좁혀졌다. 두 라이브러리의 장단점과 차이에 대해 조사해 보았다.
https://programming119.tistory.com/263
Zustand는 단일 저장소인 반면, Jotai는 함께 구성할 수 있는 원시적인 원자들로 구성되어 있다.
jotai는 컨텍스트 우선, 모듈이 그 다음 / zustand는 모듈이 우선, 컨텍스트가 그 다음이 되도록 설계되었다고 함
Zustand
import { create } from 'zustand'
type State = {
count: number
}
type Actions = {
updateCount: (
countCallback: (count: State['count']) => State['count']
) => void
}
const useCountStore = create<State & Actions>((set) => ({
count: 0,
updateCount: (countCallback) =>
set((state) => ({ count: countCallback(state.count) })),
}))
Jotai
import { atom } from 'jotai'
const countAtom = atom<number>(0)
Jotai는 원자 종속성을 통해 렌더링 최적화를 달성한다? Zustand는 selector를 사용하여 렌더링 최적화를 수동으로 적용하는 것이 좋다.
Zustand
import { create } from 'zustand'
type State = {
count: number
}
type Actions = {
updateCount: (
countCallback: (count: State['count']) => State['count']
) => void
}
const useCountStore = create<State & Actions>((set) => ({
count: 0,
updateCount: (countCallback) =>
set((state) => ({ count: countCallback(state.count) })),
}))
const Component = () => {
const count = useCountStore((state) => state.count)
const updateCount = useCountStore((state) => state.updateCount)
// ...
}
redux의 useSelector를 사용할 때 구조 분해 할당 방식을 쓰지 않거나, 다른 방식을 사용하는 것과 비슷한 걸 말하는 듯!
Zustand에서는 useCountStore가 될 것 같다.
Jotai
import { atom, useAtom } from 'jotai'
const countAtom = atom<number>(0)
const Component = () => {
const [count, updateCount] = useAtom(countAtom)
// ...
}