2. FrontEnd/State Management
[Zustand] 사용법
HyunJeongE
2023. 11. 15. 11:41
728x90
1. 설치
# NPM
npm install zustand
# Yarn
yarn add zustand
2. store만들기
나의 경우는 src폴더 안에 store폴더를 만들어 store.ts types.ts를 만들어서 상태관리를 주석처리로 구분하여 모아놨다.
import { create } from 'zustand'
const useStore = create((set) => ({
bears: 0,
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
removeAllBears: () => set({ bears: 0 }),
}))
store는 hook이다. store에 primitives, objects, functions을 넣을 수 있다. set함수가 state를 머지한다
3. 컴포넌트에서 사용하기
function BearCounter() {
const bears = useStore((state) => state.bears)
return <h1>{bears} around here...</h1>
}
function Controls() {
const increasePopulation = useStore((state) => state.increasePopulation)
return <button onClick={increasePopulation}>one up</button>
}