728x90
useReducer()
const [state, dispatchFn] = useReducer(reducerFn, initialState, initFn);
- state: The state snapshot used in the component re-render/ re-evaluation cycle
- dispatchFn: A function that can be used to dispatch a new action (i.e. trigger an update of the state)
- reducerFn: (prevState, action) => new State / A function that is triggered automatically once an action is dispatched (via dispatchFn()) - it receives the latest state snapshot and should return the new, updatedd state.
- initialState: The initial state
- initFn: A function to set the inital state programmatically.
Sample code
import { useState } from 'react';
const emailReducer = (state, action) => {
if (action.type === 'USER_INPUT') {
return { value: action.val, isValid: acion.val.includes('@') };
}
if (action.type === 'INPUT_BLUR') {
return { value: state.value, isValid: state.value.includes('@') };
}
return { value: '', isValid: false }
};
const Login = (props) => {
const [emailState, dispatchEmail] = useReducer(emailReducer, {
value: '',
isValid: null,
});
const emailChangeHandler = (event) => {
dispatchEmail({ type: 'USER_INPUPT', val: event.target.value });
setFormIsValid(
event.target.value.includes('@') && enteredPassword.trim().length > 6
);
}
const validateEmailHandler = (event) => {
dispatchEmail({ type: 'INPUT_BLUR' });
setFormIsValid(
event.target.value.includes('@') && enteredPassword.trim().length > 6
);
}
//...
};
export default Login;
useState() vs useReducer()
- useState()
- The main state management "tool"
- Great for independent pices of state/ data
- Great if state updates are easy and limited to a few kinds of updates
- useReducer()
- Great if you need "more power"
- Should be considered if you have related pieces of state/ data
- Can be helpful if you have more complex state updates
728x90
'Study Note > React' 카테고리의 다른 글
React #Building Custom Hooks (0) | 2022.09.24 |
---|---|
React #Rules of Hooks (0) | 2022.09.24 |
React #mongoose #페이지네이션 구현 (0) | 2021.03.17 |
React #joi 로 유효성 검증하기 (0) | 2021.03.17 |
React #라우트 코드 스플리팅 #비동기적으로 코드 불러오기 (0) | 2021.03.15 |
댓글