useReducer

  • ์ปดํฌ๋„ŒํŠธ ๋‚ด๋ถ€ state์˜ ์ฆ๊ฐ€๋กœ ์ธํ•œ ์ƒํƒœ๊ด€๋ฆฌ๊ฐ€ ๋ณต์žกํ•ด์งˆ ๊ฒฝ์šฐ ์‚ฌ์šฉ

  • ์ƒํƒœ ์—…๋ฐ์ดํŠธ ๋กœ์ง์„ ์™ธ๋ถ€๋กœ ๋ถ„๋ฆฌํ•  ์ˆ˜ ์žˆ์–ด ์œ ์ง€๋ณด์ˆ˜์„ฑ ์ฆ๊ฐ€

  • Dispatch ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด Action ๊ฐ์ฒด๋ฅผ Reducer๋กœ ์ „๋‹ฌํ•˜์—ฌ ์ƒํƒœ๋ฅผ ์—…๋ฐ์ดํŠธํ•จ

Youtube์ฑ„๋„ ๋ณ„์ฝ”๋”ฉ - useReducer
const initialState = {
  name: '์˜์ฐจ',
  title: '์ฃผ๋‹ˆ์–ด๊ฐœ๋ฐœ์ž',
  mentors: [
    {
      name: '์ข‹์•˜์–ด',
      title: '์‹œ๋‹ˆ์–ด๊ฐœ๋ฐœ์ž',
    },
    {
      name: '์ง„ํ–‰์‹œ์ผœ',
      title: '์‹œ๋‹ˆ์–ด๊ฐœ๋ฐœ์ž',
    },
  ],
};

type State = typeof initialState;

// ์ด๋„˜์€ ํŠน์ •๊ฐ’๋“ค์˜ ์ง‘ํ•ฉ์„ ์˜๋งˆํ•˜๋Š” ์ž๋ฃŒํ˜•์ด๋‹ค.
// ์•„๋ž˜๋Š” ๋ฌธ์žํ˜• ์ด๋„˜
export enum ACTION_TYPE {
  UPDATED = 'updated',
  ADDED = 'added',
  DELETED = 'deleted',
}

/*
  | { type: 'updated', payload: { prev: string, current: string } }
  | { type: 'added', payload: { name: string, title: string }}
  | { type: 'deleted', payload: { name: string }};
*/

type PersonAction = {
  type: ACTION_TYPE,
  payload: {
    prev?: string;
    current?: string;
    name?: string;
    title?: string;
  }
}

export function reducer(
  state: State = initialState,
  { type, payload }: PersonAction,
): State {
  switch (type) {
  case ACTION_TYPE.UPDATED:
    return {
      ...state,
      mentors: state.mentors.map((mentor) => {
        if (mentor.name === payload.prev) {
          return { ...mentor, name: payload.current ?? '' };
        }
        return mentor;
      }),
    };
  case ACTION_TYPE.ADDED:
    return {
      ...state,
      mentors: [...state.mentors, {
        name: payload.name ?? '',
        title: payload.title ?? '',
      }],
    };
  case ACTION_TYPE.DELETED:
    return {
      ...state,
      mentors: state.mentors.filter((mentor) => mentor.name !== payload.name),
    };
  default:
    return state;
  }
}
const [person, dispatch] = useReducer(personReducer, initPersonState);

Last updated