UseReducer

reducer์˜ ์žฅ์ 

๋กœ์ง ๋ถ„๋ฆฌ

์ƒํƒœ ์ €์žฅ ์‹œ ํ•„์š”ํ•œ ๋กœ์ง์„ reducer๋กœ ๋ถ„๋ฆฌํ•˜์—ฌ ์‚ฌ์šฉ

useReducer ์‚ฌ์šฉ๋ฒ•

์ฐธ์กฐ

const [state, dispatch] = useReducer(reducer, initialArg, init?)

์‚ฌ์šฉ๋ฒ•

  1. ๋ฆฌ๋“€์„œ ์ƒ์„ฑ

const todosReducer = (draft: Todo[], action: Action) => {
  switch (action.type) {
    case "add": {
      const { title } = action;
      draft.push({ id: crypto.randomUUID(), title });
      return;
    }
    default: {
        throw Error('Unknown action: ' + action.type);
      }
  }
};
  1. ์ดˆ๊ธฐ ์ƒํƒœ ์ƒ์„ฑ

const INITIAL_TODOS = [
  { id: crypto.randomUUID(), title: "์ฒซ ๋ฒˆ์งธ ํ•  ์ผ" },
];
  1. ์ปดํฌ๋„ŒํŠธ์—์„œ useReducer๋ฅผ ์‚ฌ์šฉ

const [todos, dispatchTodos] = useImmerReducer<Todo[]>(
    todosReducer,
    INITIAL_TODOS,
  );
  1. dispatch๋ฅผ ํ†ตํ•ด ์ƒํƒœ ๋ณ€๊ฒฝ

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (!title) return;
    dispatchTodos({ type: "add", title });
    clearTitle();
  };

๋ฆฌ๋“€์„œ ์ž‘์„ฑ

  • ๋ฆฌ๋“€์„œ๋ฅผ ์ˆœ์ˆ˜ํ•˜๊ฒŒ ์ž‘์„ฑ: ๋ถ€์ž‘์šฉ ์—†์ด ์ƒํƒœ๋ฅผ ์—…๋ฐ์ดํŠธ

  • ๊ฐ ์ž‘์—…์„ ํ•˜๋‚˜์˜ ์‚ฌ์šฉ์ž ์ƒํ˜ธ ์ž‘์šฉ์œผ๋กœ ์„ค๋ช…: ์—ฌ๋Ÿฌ ์ž‘์—…์„ ๊ฐ๊ฐ ์ „๋‹ฌํ•˜์ง€ ๋ง๊ณ  ํ•˜๋‚˜์˜ ์ž‘์—…์œผ๋กœ ์ „๋‹ฌํ•˜๋Š” ๊ฒƒ์ด ํ•ฉ๋ฆฌ์ 

Last updated