src/store/count.ts
import { create } from "zustand";
//store 타입
type Store = {
count: number;
increase: () => void;
decrease: () => void;
};
set, get 매개변수export const useCountStore = create<Store>((set, get) => ({
count: 0,
increase: () => {
// 1. 값을 셋할수 있는 첫번째 방법
const count = get().count;
// 카운트만 바꿔도 명시되어있지 않은 다른 값들은 그대로 있음
set({ count: count + 1 });
// 2. 값을 셋할수 있는 두번째 방법
//함수형 업데이트
//(복잡)
set((store) => {
return {
count: store.count + 1,
};
});
//(간결)
set((store) => ({ count: store.count + 1 }));
},
decrease: () => {
set((store) => ({ count: store.count - 1 }));
},
}));
스토어 안에 함수 만들기 / 값을 set할수 있는 두가지 방법
increase: () => {
const count = get().count;
// 카운트만 바꿔도 명시되어있지 않은 다른 값들은 그대로 있음
set({ count: count + 1 });
},
두번째 방법(함수형 업데이트, set 함수 바로 사용하기)
increase: () => {
set((store) => {
return {
count: store.count + 1,
};
});
},
increase: () => {
set((store) => ({ count: store.count + 1 }));
},import { Button } from "@/components/ui/button";
import { useCountStore } from "@/store/count";
export default function CounterPage() {
//zustand 스토어 훅 불러오기
⭐️ const { count, increase, decrease } = useCountStore();
return (
<div>
<h1>카운터 페이지</h1>
<div>{⭐️ count}</div>
<div>
<Button onClick={⭐️ increase}>+</Button>
<Button onClick={⭐️ decrease}>-</Button>
</div>
</div>
);
}