[React.js] useReducer


useReducer

useState์˜ ๋Œ€์ฒด ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค.

(state, action) => newState์˜ ํ˜•ํƒœ๋กœ reducer๋ฅผ ๋ฐ›๊ณ  (ํ•„์ˆ˜) dispatch ๋ฉ”์„œ๋“œ์™€ ์ง์˜ ํ˜•ํƒœ๋กœ ํ˜„์žฌ state๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

์‚ฌ์šฉํ•˜๋Š” ์ด์œ 

  • ๋‹ค์ˆ˜์˜ ํ•˜์œ—๊ฐ’์„ ํฌํ•จํ•˜๋Š” ๋ณต์žกํ•œ ์ •์  ๋กœ์ง์„ ๋งŒ๋“œ๋Š” ๊ฒฝ์šฐ
  • state๊ฐ€ ์ด์ „ state์— ์˜์กด์ ์ธ ๊ฒฝ์šฐ์— ๋ณดํ†ต useState๋ณด๋‹ค useReducer๋ฅผ ์„ ํ˜ธ
  • useReducer๋Š” ์ž์„ธํ•œ ์—…๋ฐ์ดํŠธ๋ฅผ ํŠธ๋ฆฌ๊ฑฐ ํ•˜๋Š” ์ปดํฌ๋„ŒํŠธ์˜ ์„ฑ๋Šฅ์„ ์ตœ์ ํ™”ํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•˜๋Š”๋ฐ, ์ด๊ฒƒ์€ ์ฝœ๋ฐฑ ๋Œ€์‹  dispatch๋ฅผ ์ „๋‹ฌ ํ•  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ
  1. state : ์ƒํƒœ๋ฐ์ดํ„ฐ (์ด๋ฅผ ์ž„์˜ ์ •์˜)

  2. dispatch: ์•ก์…˜์„ ๋ฐœ์ƒ์‹œํ‚ค๋Š” ํ•จ์ˆ˜ (์•ก์…˜์„ ๋ณด๋‚ด๋Š”๊ณณ,์—ฐ๊ฒฐ,์ „๋‹ฌ์ž)

  3. reducer : ์ƒํƒœ๋ถ„๋ฆฌ๋กœ์˜ ํ•จ์ˆ˜ (์ด๋ฆ„ ์ž„์˜์ •์˜)

  4. initialArg : ์ดˆ๊ธฐ๊ฐ’


๊ธฐ๋ณธ๊ฐ’

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

useReducer(์ƒํƒœ ์—…๋ฐ์ดํŠธ ๋กœ์ง์„ ๋‹ด์€ ํ•จ์ˆ˜, ์ดˆ๊ธฐ๊ฐ’)

์ด๋ฒคํŠธ = dispatch({type: "์•ก์…˜๋ช…"}) - dispatch์˜ ํƒ€์ž…์€ ํ•„์ˆ˜

์•ก์…˜๋ช… : ๋ณ„์นญ ,๋ณ„๋ช…
        ์˜๋ฌธ ์†Œ๋ฌธ์ž ,๋Œ€๋ฌธ์ž ,ํ•œ๊ธ€ ๊ฐ€๋Šฅ / ํ•˜์ง€๋งŒ ๋Œ€๋ฌธ์ž(์ƒ์ˆ˜ํ˜•)๋กœ ์“ฐ๋Š”๊ฒŒ ์ข‹๋‹ค

    dispatch({type: 'ํ•„์ˆ˜'})
    dispatch({type: 'ํ•„์ˆ˜', ํ‚ค1:๊ฐ’})
    dispatch({type: 'ํ•„์ˆ˜', ํ‚ค1:๊ฐ’, ํ‚ค2:๊ฐ’})

์ƒํƒœ ๋กœ์ง ๋ถ„๋ฆฌ
  1. ๊ธฐ๋ณธ ์นด์šดํŠธ ํ•จ์ˆ˜ ๊ตฌํ˜„
import React from "react";
import { useReducer } from "react";

//์ดˆ๊ธฐ๊ฐ’

const initialState = 0;

//๋ถ„๋ฆฌ

const reducer = (state, action) => {
  switch (action.type) {
    case "INCREMENT":
      return state + action.step;
    case "DECREMENT":
      return state - action.step;
    case "RESET":
      return 0;
    default:
      return state;
  }
};

const Test1_step = () => {
  //์—ฐ๊ฒฐ
  const [count, dispatch] = useReducer(reducer, initialState);

  return (
    <div>
      <h1>์นด์šดํŠธ : {count}</h1>
      <p>
        <button onClick={() => dispatch({ type: "INCREMENT", step: 10 })}>
          10์”ฉ ์ฆ๊ฐ€ : INCREMENT
        </button>
        <button onClick={() => dispatch({ type: "DECREMENT", step: 20 })}>
          20์”ฉ ๊ฐ์†Œ : DECREMENT
        </button>
        <button onClick={() => dispatch({ type: "RESET" })}>
          ์ดˆ๊ธฐํ™” : RESET
        </button>
      </p>
    </div>
  );
};

export default Test1_step;
  1. ๊ตฌํ˜„ ์˜์ƒ

useReducer_Timer