[react] react zustand 첫 인상

protomothis·2023년 1월 14일
0

React

목록 보기
1/2
post-thumbnail

들어가며

사실 react를 제대로 접한 지는 얼마 되지 않았는데, vue와 달리 react에서는 상태 관리를 위한 솔루션이 여러 가지로 많았다.
가장 기본으로는 redux가 있었고, MobX, Recoil, zustand 등..

그 중에서도 zustand를 러닝 커브에 있어서도 장점이 있었고 적은 보일러플레이트, 디버그의 용이성, 제어의 복잡성이 떨어지지 않아 사용해보기로 하였다.

어느 정도 react hook에 대해서 익숙해졌기 때문에 react 환경에서 zustand를 사용하는 데에는 큰 무리가 없었다.

zustand, 한번 사용해보자

// 예를 들어서 상품을 관리하는 전역 스토어를 만들자면...

// 상품을 구성하는 모델이다.
export interface MyProduct {
  itemNo: number;
  itemName: string;
  imageUrl: string;
  price: number;
  recommandRate: number;
  usableCoupons?: boolean;
}

// states에 대한 선언
export interface MyProductsStoreStates {
  productList: MyProduct[];
}

// states 에 대한 mutation 등 처리를 하는 actions 에 대한 선언
export interface MyProductsStoreActions {
  actions: {
    setProductList: (products: MyProduct[]) => void;
  };
}

// states 와 action 으로 구성된 스토어 모델을 선언
export interface MyProductsStore extends IProductsStoreStates, IProductsStoreActions {}

// zustand create api로 store 생성
const useMyProductsStore = create<MyProductsStore>((set, get) => ({
  // region states
  productList: initialState.productList,
  // endregion

  // region actions
  actions: {
    // productlist 를 설정하는 action.
    setProductList: (products) => set((state) => ({
      ...state,
      productList: products,
    })),
  }
  // endregion
}));

// region hooks
export const useMyProductList = () => useMyProductsStore((state) => state.productList, shallow);
export const useMyProductsStoreActions = () => useMyProductsStore((state) => state.actions);
// endregion

상품 리스트에 대한 상태를 설정하고, 해당 리스트를 가져오는 훅을 선언했다.
이를 아래와 같이 컴포넌트에서 사용할 수 있다.

export default function Products() {
  // region hook states
  const productList = useMyProductList();
  const { setProductList } = useMyProductsStoreActions();
  ...

정말 간단하게 상태관리를 할 수 있다고 생각한 대목이다.
이제 react-query와 같은 api 상태관리 라이브러리와 함께 사용하게 된다면 어떤 구조로 구현하는 것이 더 합리적일까 고민해 볼 생각이다.

profile
frontend dev, home server lover.

0개의 댓글