DAY2 - 한입 실전 프로젝트(zustand)

짱효·2025년 11월 12일

Zustand

src/store/count.ts

  1. state, action 함수를 포함하는 객체인 store 를 생성
import { create } from "zustand";
  1. 스토어 타입 지정
//store 타입
type Store = {
  count: number;
  increase: () => void;
  decrease: () => void;
};
  1. create 함수 안에 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 }));
  },
}));
  1. 스토어 안에 함수 만들기 / 값을 set할수 있는 두가지 방법

    1. 첫번째 방법(값을 get해서 사용하기)
    increase: () => {
        const count = get().count;
        // 카운트만 바꿔도 명시되어있지 않은 다른 값들은 그대로 있음
        set({ count: count + 1 });
    
      },
    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>
  );
}
profile
✨🌏확장해 나가는 프론트엔드 개발자입니다✏️

0개의 댓글