Post

[iPlan 프로젝트] 상태 관리 리팩토링 (Context API & Reducer)

[iPlan 프로젝트] 상태 관리 리팩토링 (Context API & Reducer)

React Native 앱에서 Plan과 Reward 기능을 Context API와 Reducer로 리팩토링하는 과정과 코드를 정리합니다.


📌 프로젝트 구조 리팩토링

이번 리팩토링의 목표는 기존 useState로 관리하던 Plan과 Reward 상태를 Context APIReducer로 관리하여 유지보수성을 높이는 것입니다.

🔨 PlanContext, RewardContext 정의하기

📂 context/plan/planReducer.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
export interface Plan {
  id: string;
  title: string;
  post_date: string;
  is_completed: boolean;
}

type PlanState = { plans: Plan[]; };

type PlanAction =
  | { type: 'SET_PLANS'; payload: Plan[] }
  | { type: 'ADD_PLAN'; payload: Plan }
  | { type: 'UPDATE_PLAN'; payload: Plan };

const planReducer = (state: PlanState, action: PlanAction): PlanState => {
  switch (action.type) {
    case 'SET_PLANS':
      return { plans: action.payload };
    case 'ADD_PLAN':
      return { plans: [...state.plans, action.payload] };
    case 'UPDATE_PLAN':
      return {
        plans: state.plans.map(plan =>
          plan.id === action.payload.id ? action.payload : plan
        ),
      };
    default:
      return state;
  }
};

export default planReducer;
This post is licensed under CC BY 4.0 by the author.