useState
를 대체할 수 있는 함수useState
dispatch
함수를 전달할 수 있기 때문)import {useReducer} from 'react';
const [state, dispatch] = useReducer(reducer, initialState,init);
reducer 함수를 실행시킴
action 객체를 인자로 받으며, action 객체는 어떤 행동인지를 나타내는 type 속성과 해당 행동과 관련된 데이터(payload) 를 담고 있음
action 을 이용하여 컴포넌트 내에서 state의 업데이트를 일으킴
action 사용 예시
<button onClick = {() => dispatch(
{type: 'INCREMENT'}
)}>
증가
</button>
①. action type만 정의한 경우
export default function reducer(state, action) {
switch(action.type)
case 'INCREMENT':
return {count: state.count +1};
case 'DECREMENT':
return {count : state.count -1};
default :
throw Error ("unsupported action type: ",action.type);
}
}