React

[React] 전역 상태 관리 Zustand 사용해보기

woo.oing 2025. 10. 28. 13:39

아래 강의를 수강하며 배운 내용을 정리한 글입니다

[한 입 크기로 잘라먹는 실전 프로젝트 - SNS 편 - 이정환] https://inf.run/SbJ8w

 

 

가볍고 배우기 쉬운 간단한 사용법으로 react 상태 관리 라이브러리로 가장 많이 사용한다는 zustand를 처음 사용해 봤습니다

react 프로젝트에 설치부터 사용까지 작성해 보겠습니다!

 

 

https://zustand.docs.pmnd.rs/getting-started/introduction

 

Introduction - Zustand

How to use Zustand

zustand.docs.pmnd.rs

 

 

1. 설치하기

터미널에 아래 명령어 입력

npm install zustand

 

 

2. 사용해 보기

create에서 set, get을 사용하여 값을 가져오고 설정할 수 있습니다

-  set: 상태 변경 함수
-  get: 현재 상태 조회 함수

 

구현 예시 코드는 아래와 같습니다

// count.ts

type Store = {
  count: number;
  actions: {
    increase: () => void;
    decrease: () => void;
  };
};

export const useCountStore = create<Store>((set, get) => ({
  count: 0,
  actions: {
    increase: () => {
      // 1
      // const count = get().count;
      // set({ count: count + 1 });

      // 2: 함수형 업데이트
      set((state) => ({ count: state.count + 1 }));
    },
    decrease: () => {
      set((state) => ({ count: state.count - 1 }));
    },
  },
}));

export const useCount = () => {
  const count = useCountStore((store) => store.count);
  return count;
};

export const useIncreaseCount = () => {
  const increase = useCountStore((store) => store.actions.increase);
  return increase;
};

export const useDecreaseCount = () => {
  const decrease = useCountStore((store) => store.actions.decrease);
  return decrease;
};

 

위에서 생성했던 useCountStore를 호출하면 count, increase, decrease를 가져와 사용할 수 있습니다

// controller.tsx

export default function Controller() {
  const increase = useIncreaseCount();
  const decrease = useDecreaseCount();
  // const { increase, decrease } = useCountStore((state) => state.actions);

  return (
    <div>
      <Button onClick={decrease}>-</Button>
      <Button onClick={increase}>+</Button>
    </div>
  );
}
// viewer.tsx

export default function Viewer() {
  const count = useCount();

  return <div>{count}</div>;
}

 

 

다음 글 보기 →

 

[React] 전역 상태 관리 Zustand의 미들웨어 사용해 보기

이전 글에 이어서 이번에는 zustand의 middlewares를 사용해 보겠습니다 ← 이전 글 보기 [React] 전역 상태 관리 Zustand 사용해보기가볍고 배우기 쉬운 간단한 사용법으로 react 상태 관리 라이브러리로

woooing.tistory.com