zustand는 redux, mobX와 같은 상태관리 라이브러리다.
전자와 후자 둘의 차이점을 꼽아보자면,
zustand는 상태관리에 필요한 최소한의 api를 제공하여 간단하게 사용하는 것이
목표라고 할 수 있겠다.
또한 redux에 작성하던 것처럼 액션과 리듀서를 작성할 필요가 없다.
redux와 달리 zustand에서는 상태를 직접 변경할 수 있기 때문이다.
이러한 이유로 zustand는 조금 더 직관적인
라이브러리라 할 수 있겠다.
import create from 'zustand'
const useStore = create(set => ({
bears: 0,
increasePopulation: () => set(state => ({ bears: state.bears + 1 })),
removeAll: () => set({ bears: 0 })
}))
function BearCounter() {
const bears = useStore(state => state.bears)
return <h1>{bears} around here ...</h1>
}
function Controls() {
const increasePopulation = useStore(state => state.increasePopulation)
const removeAll = useStore(state => state.removeAll)
return (
<>
<button onClick={increasePopulation}>one up</button>
<button onClick={removeAll}>remove all</button>
</>
)
}
위는 zustand를 써서 만든 간단한 예제 코드이다.
사용법은 아래와 같다.
// store.module.ts
// js
import {create} from 'zustand'
export const projectName = create((set) => ({
state: 0,
setState: (newState) => set({state: newState})
}))
// ts
interface State1 {
state: number
setState: (newState: number) => void
}
export const projectName = create<State1>((set) => ({
state: 0,
setState: (newState) => set({state: newState})
}))
// hello.tsx
import { projectName } from './store.module'
const hello = () => {
const { state, setState } = projectName()
return (
<div>{state}</div>
)
}
zustand와 react Query를 같이 써야 하는 이유는?
zustand는 미니멀한 상태 관리 라이브러리이고, 전역 상태를 관리한다.
react query는 data를 가져오는 라이브러리이다. 서버 상태 관리에 용이하다.
react query는 서버 상태에 대한 캐싱, 동기화 및 백그라운드 업데이트를 지원하는데,
기본적으로 데이터를 가져오고 동기화를 관리하기 위해 효과 및 상태를 사용할 필요가 없다.
그렇다면 이 두 개를 같이 쓰는 이유는 무엇인가하면,
클라이언트 상태에 관해서는 zustand를 사용하고, 서버 상태에 반응하는 react query를 통해
안정성을 도모하는 것이다.
두 라이브러리의 강점을 활용하여 프로젝트에 적용해 볼 예정이다.