개발 일기
2024-11-27(상태관리,zustand)
민ズl
2024. 11. 27. 17:13
클라이언트 상태 관리 예시
- 폼 입력값
- 인증상태 (로그인/로그아웃)
- 프로필정보
- 테마 모드
- 언어 설정
- 모달 열림 상태
- 탭 및 사이드바 상태
서버 상태 관리
- 항상 최신 상태로 DB와 동기화가 필요할때
- 다른 사용자에게 영향을 줄 수 있는 데이터
- 데이터를 가져오는 데 시간이 소요되고(로딩스피너 필요) 잦은 조회로 캐싱이 필요한 데이터
zustand
import {create} from 'zustand';
const useCalculatorstore = create((set)) => ({
result : 0,
incrementByAmount: (amount) => {
set(({result}) => ({result : result + amount}));
},
decrementByAmount : (amout) => {
set(({result}) => ({result : result - amount}))
},
})
//immer버전
import {immer} from 'zustand/middleware/immer';
const useCalculatorStore = create(
immer((set) => ({
result: 0,
incrementByAmount: (amount) => {
set((state) => {
state.result += amount;
});
},
decrementByAmount: (amount) => {
set((state) => {
state.result -= amount;
});
},
}))
);