[TIL] React useReducer

kiyeol·2021년 2월 22일

useReducer란?

현재 상태와 액션 객체를 파라미터로 받아와서 새로운 상태를 반환해 주는 Hook

현재 state와 action 객체를 받아와서 action.type에 따라서 state 값을 반환해주는 함수이다.

fuction reducer(state, action) {
  switch(action.type) {
    	case 'INCREMENT':
        	return state + 1;
        case 'DECREMENT':
        	return state - 1;
        default:
      		return state;
    }
}

number - 현재 상태
dispatch - 액션을 발생 시키는 함수

const [number, dispatch] = useReducer(reducer, 0);

 const onIncrease = () => {
    dispatch({ type: 'INCREMENT' });
  };

  const onDecrease = () => {
    dispatch({ type: 'DECREMENT' });
  };

참조)
https://react.vlpt.us/basic/20-useReducer.html

profile
kyday63@gamil.com

0개의 댓글