-
Notifications
You must be signed in to change notification settings - Fork 47
[7팀 박희정] Chapter3-2. 디자인 패턴과 함수형 프로그래밍 그리고 상태 관리 설계 #40
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Pheejung
wants to merge
20
commits into
hanghae-plus:main
Choose a base branch
from
Pheejung:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
**Header 컴포넌트 개선:** - Props 타입 정의 (HeaderProps 인터페이스 추가) - 상태 관리를 부모 컴포넌트로 위임 (단일 책임 원칙) - useMemo를 활용한 장바구니 카운트 최적화 - 불필요한 초기 데이터 및 로직 제거 **재사용 가능한 Custom Hook 추가:** - useDebounce: 값 변경 지연으로 성능 최적화 - useLocalStorage: React 상태와 localStorage 자동 동기화 - shared/hooks에 유틸리티 Hook 모듈화
- AdminPage 컴포넌트 생성 및 admin UI 분리
**widgets 폴더 생성** - Header (기존 shared/layout에서 이동) - NotificationList (App.tsx에서 분리) **shared 폴더 재구성** - hooks/ (useDebounce, useLocalStorage)
- Props 기반 아키텍처로 상태/액션 전달
- Props 기반 아키텍처로 상태/액션 전달
**entities 파일 생성 (cart, product, coupon)** - 타입 정의 (model.ts) - 순수 함수 (utils.ts)
- formatPrice: 가격 표시 (1000 → "1,000원") - formatDiscount: 할인율 표시 (0.1 → "10%") - generateOrderNumber: 주문번호 생성
- Button 컴포넌트 (4가지 variant, 3가지 size) - Input 컴포넌트 (label, error 지원, forwardRef) - Badge 컴포넌트 (5가지 variant, 숫자 표시) - Card 컴포넌트 (padding, shadow 커스터마이징) - TailwindCSS 기반 재사용 가능한 UI 구축
- features/ → hooks/ (상태 관리) + widgets/ (UI 컴포넌트)
- Jotai atom 구조로 전역 상태 재구성
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
과제의 핵심취지
https://pheejung.github.io/front_7th_chapter3-2/index.basic.html
https://pheejung.github.io/front_7th_chapter3-2/index.advanced.html
과제에서 꼭 알아가길 바라는 점
기본과제
Component에서 비즈니스 로직을 분리하기
비즈니스 로직에서 특정 엔티티만 다루는 계산을 분리하기
뷰데이터와 엔티티데이터의 분리에 대한 이해
entities -> features -> UI 계층에 대한 이해
Component에서 사용되는 Data가 아닌 로직들은 hook으로 옮겨졌나요?
주어진 hook의 책임에 맞도록 코드가 분리가 되었나요?
계산함수는 순수함수로 작성이 되었나요?
Component에서 사용되는 Data가 아닌 로직들은 hook으로 옮겨졌나요?
주어진 hook의 책임에 맞도록 코드가 분리가 되었나요?
계산함수는 순수함수로 작성이 되었나요?
특정 Entitiy만 다루는 함수는 분리되어 있나요?
특정 Entitiy만 다루는 Component와 UI를 다루는 Component는 분리되어 있나요?
데이터 흐름에 맞는 계층구조를 이루고 의존성이 맞게 작성이 되었나요?
심화과제
이번 심화과제는 Context나 Jotai를 사용해서 Props drilling을 없애는 것입니다.
어떤 props는 남겨야 하는지, 어떤 props는 제거해야 하는지에 대한 기준을 세워보세요.
Context나 Jotai를 사용하여 상태를 관리하는 방법을 익히고, 이를 통해 컴포넌트 간의 데이터 전달을 효율적으로 처리할 수 있습니다.
Context나 Jotai를 사용해서 전역상태관리를 구축했나요?
전역상태관리를 통해 domain custom hook을 적절하게 리팩토링 했나요?
도메인 컴포넌트에 도메인 props는 남기고 props drilling을 유발하는 불필요한 props는 잘 제거했나요?
전체적으로 분리와 재조립이 더 수월해진 결합도가 낮아진 코드가 되었나요?
과제 셀프회고
처음에는 어떻게 나눠야 할지, 순수함수의 기준은 무엇인지, hook에 무조건 하나의 함수만 들어가야 하는건지, 그 기준이 무엇인지 등등 설계와 명확한 기준을 나누는 게 제일 힘들었습니다.
그래서 제가 제일 먼저 한 건 UI를 나누는 것이었습니다. Header, AdminPage, CartPage, Toast 같은 화면 영역을 먼저 widgets와 pages로 구분하고, 그 다음에 각 화면이 필요로 하는 데이터와 로직을 역으로 추적해가며 entities와 hooks를 분리해나갔습니다.
내가 거쳐온 리팩토링 단계
1단계 - UI 먼저 쪼개기
처음 코드는 App.tsx에 모든 게 섞여 있었습니다. 제일 먼저 눈에 보이는 UI부터 나누었습니다.
HeaderCartPageAdminPage2단계 - 순수 계산 로직 분리
CartPage컴포넌트 안에서 직접cart.reduce()로 합계를 계산하던 코드를 발견했습니다. "이건 UI가 아니라 계산이잖아?"라는 생각이 들어서entities/cart/utils.ts로 빼냈습니다.처음엔 "아이템 하나 계산하는데 왜 cart 전체가 필요해?"라고 생각했는데, 대량 구매 보너스(
hasBulkPurchase) 때문에 전체 장바구니를 봐야 했습니다. 순수 함수인 건 맞지만 인자가 많아서 찝찝했습니다.3단계 - Hook으로 상태 + 액션 묶기
계산 함수를 분리하고 나니, 이제 "상태를 어떻게 관리할까?"가 문제였습니다. 각 도메인(cart, product, coupon)별로 훅을 만들고 심화과정 advanced에서 Jotai atom를 사용해 전역 상태로 구현하였습니다.
재고 부족 같은 에러를 훅에서 처리하니 컴포넌트는 깔끔해졌는데 "
addToast를 hook이 직접 호출하는 게 맞나?", "토스트 표시는 UI 관심사 아닌가?" 싶어서 컴포넌트로 빼야 할지 계속 고민했습니다.4단계 - Props Drilling 지우기 (심화과정 Jotai 도입)
CartPage에서Cart→CartItem으로 props를 3단계로 내려주는 게 너무 불편했습니다.최종 구조
과제를 하면서 내가 알게된 점, 좋았던 점은 무엇인가요?
UI-우선 슬라이싱이 기준을 만든다
로직/도메인부터 쪼개려다 기준이 흐려졌는데, 화면(Header/Admin/Cart/Toast)부터 가르니 “어떤 데이터/액션이 진짜 필요하냐”가 선명해졌고 이후 entities → hooks → widgets/pages로 자연스럽게 내려갈 수 있었습니다.
순수 함수로의 분리가 테스트와 리팩터링 속도를 바꾼다
합계/할인/재고 검증을 entities/*로 뺀 뒤엔 훅/컴포넌트 테스트가 아니라 함수 단위 테스트만으로 회귀를 잡을 수 있었습니다. 덕분에 계산 규칙이 바뀌어도 UI는 손대지 않았던 것 같습니다.
"비즈니스 로직은 entities, 상태 관리는 hooks" 즉 "도메인 규칙은 순수 함수로, 상태 조작은 Hook으로"
훅에서 상태 전환과 액션 배선만 맡기고, entities로 순수 함수를 분리하니 훅은 "언제 어떤 함수를 호출할지"만 책임지게 되어 훨씬 읽기 쉬워졌습니다.
이번 과제를 통해 앞으로 해보고 싶은게 있다면 알려주세요!
1. 상태관리 라이브러리 심층 비교
Jotai를 사용하면서 atom 기반 상태관리의 편리함을 경험했는데, 다른 라이브러리들과 직접 비교해보고 싶습니다.
특히 이번 과제에서
atomWithStorage로 localStorage 동기화를 간단하게 처리했는데, 다른 라이브러리에서는 이런 기능을 어떻게 구현하는지, 각 라이브러리의 장단점을 실제 코드로 비교해보고 싶습니다.2. 함수형 프로그래밍 패턴 적용
이번 과제에서 순수 함수를 분리하면서 함수형 프로그래밍의 장점을 조금 경험해봤는데, 더 깊이 있게 공부하고 싶습니다.
구체적으로 배우고 싶은 것들:
setCart(prev => addProductToCart(prev, product))같은 패턴을 더 우아하게 작성하는 방법pipe,compose)리뷰 받고 싶은 내용이나 궁금한 것에 대한 질문 편하게 남겨주세요 :)
1. 훅의 책임 범위
현재
useCart훅:질문:
useCart가 너무 많은 책임을 지고 있는 것 같은데, 제가 잘못 설계한걸까요?2. Props 분리 기준