Reducer란?
- useState같이 state관리를 도와주는 Hook이며, useState보다 강력하다.
- 특히 여러 state와 연관된 state 등, 복잡한 상태 관리에 사용한다.
- 강력하지만 사용하기 복잡해, 일반적인 상태는 useState를 사용하는 게 좋다.
Reducer를 사용할 때?
const Component = (props) => {
const [enteredEmail, setEnteredEmail] = useState("");
const [emailIsValid, setEmailIsValid] = useState("");
const emailChangeHandler = (event) => {
setEnteredPassword(event.target.value);
}
const validateEmailHandler = () => {
setEmailIsValid(enteredEmail.includes('@'));
}
- 위 코드는 emailIsValid를 설정하기 위해, 다른 state인 enteredEmail를 참조하고 있다.
- 이 경우, React의 State 업데이트 정책에 의해 enteredEmail가 최신값이 아닐 수 있다.
- React는 State의 업데이트가 필요할 때, 여러 개를 묶어서 비동기적으로 처리한다.
- 만약 컴포넌트의 규모가 크면, 수많은 state를 각각 업데이트 할 시 overhead가 크기 때문이다.
- 이처럼, 여러 State가 서로 연관된 복잡한 상태관리는 Reducer로 관리하는게 더 낫다.
Reducer를 사용해 보자
const emailReducer = (state, actions) => {
if(actions.type === 'USER_INPUT')
return {value: actions.val, isValid: actions.val.includes('@')};
if (actions.type === 'INPUT_BLUR')
return {value: state.value, isValid: state.value.includes('@')};
return {value: '', isValid: false};
};
const Component = (props) => {
const [emailState, dispatchEmail] = useReducer(emailReducer, {
value: '',
isValid: undefined,
});
const emailChangeHandler = (event) => {
dispatchEmail({type: 'USER_INPUT', val: event.target.value});
}
const validateEmailHandler = () => {
dispatchEmail({type: 'INPUT_BLUR'})
};
- Reducer를 사용해, Email 값과 유효 여부를 함께 관리하고 있다.
- emailState에 접근하기 위해, dispatchEmail 함수를 사용한다.
- 이 때, 인수로 넘겨주는 Object가 EmailReducer의 actions 파라미터가 된다.
- email 값의 검증하기 위해, emailReducer의 state 파라미터를 참조하고 있다.
- state 파라미터는 emailState의 이전 상태로, 항상 최신 값이라고 보증할 수 있다.