useState vs useReducer

minho·2022년 4월 11일
0

useState


useState는 쉽게말하면 고객이 장부를 직접 수정하는 경우이다.

const [count,setCount] = useState(0) //count는 장부

const down() => { //고객
  setCount(count-1);
}

const up() => { //고객
  setCount(count+1);
}

const reset() => { //고객
  setCount(count = 0);
}

setCount라는 리모컨을 이용해서 count를 조작한다.
그러나 고객들이 많아지면 관리하기 어렵다!
그래서 많은 고객들을 관리하기 위해 useReducer를 사용한다.

useReducer

//state는 장부, reducer는 회계직원, action은 직원
const reducer = (state, action) => { 
    switch (action.type) {
        case "SAVE":
            return state + action.inputMoney;
        case "OUTPUT":
            return state - action.outputMoney;
        default:
            return state;
    }
}
//dispatch는 창구직원, save,out은 각각 고객의 요구사항
const Example = () => {
    const[state,dispatch] = useReducer(reducer, 100);

    const save = () => {
      dispatch({
        type: "SAVE",
        inputMoney: 100,
      });
    };

    const out = () => {
      dispatch({
        type: "OUTPUT",
        outputMoney: 50,
      });
    };
    return(
        <div>
            {state}
            <button onClick={save}>save</button>
            <button onClick={out}>out</button>           
        </div>
    ) 
}

고객이 저금(save)를 요청하는 경우

0. 준비

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

state는 장부이며, dispatch는 고객의 요구사항을 전달하는 창구직원이다.
숫자 100은 state의 초기값이다.

1. save함수 실행

const save = () => {
      dispatch({
        type: "SAVE",
        inputMoney: 100,
      });
    };
  • 고객은 type: "SAVE"를 창구직원에게 요청한다.
  • imputMoney는 SAVE를 실행하기 위한 준비물이다.

2. reducer실행

action은 고객이 요청한 type:"SAVE"를 실행하는 함수이다.

const reducer = (state, action) => { 
    switch (action.type) {
        case "SAVE":
            return state + action.inputMoney;
        case "OUTPUT":
            return state - action.outputMoney;
        default:
            return state;
    }
}
  • 고객이 SAVE를 요청했으니 case가 SAVE인것을 실행한다.
  • action.inputMoney는 1에서의 준비물이다.
profile
Live the way you think

0개의 댓글