기존 코드 const [emailAlert, setEmailAlert] = useState(''); const [passwordAlert, setPasswordAlert] = useState(''); const [pwCheckAlert, setPwCheckAlert] = useState(''); const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); 수정 코드 const [alert, dispatch] = useReducer(reducer, initialState); const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [pwCheck, setPwCheck] = useState('');
- state는 3개의 Alert state를 alert 하나의 state에서 관리될 수 있도록 변경했다.
변경된 코드
초기값 설정 const initialState = { emailAlert: {message: '', status: ''}, //message는 유효성 검사 알림 메세지 passwordAlert: {message: '', status: ''}, // status는 antd 속성값을 주기위함 pwCheckAlert: {message: '', status: ''}, }; type 관리 const actions = { // action.type을 한 곳에서 관리하기 위해 객체로 할당 EMAILCHECK: 'EMAILCHECK', PASSWORDCHECK: 'PASSWORDCHECK', PWCHECK: 'PWCHECK', }; reducer 함수 const reducer = (alert, action) => { const {EMAILCHECK, PASSWORDCHECK, PWCHECK} = actions; switch (action.type) { case EMAILCHECK: return { ...alert, emailAlert: action.emailAlert, }; case PASSWORDCHECK: return { ...alert, passwordAlert: action.passwordAlert, }; case PWCHECK: return { ...alert, pwCheck: action.pwCheckAlert, }; default: return { ...alert, }; } };
- alert는 객체로 구성되어 있기 때문에 직접 값을 할당하면 불변성이 지켜지지 않기 때문에 spread operator를 통해 기존의 값에 property값을 덮어씌웠다.
- 코드의 양 자체는 오히려 늘었지만 하나의 함수에서 관리할 수 있기 때문에 유지보수 효율이 더 올라간다고 생각했다.
- useState와 uesReducer는 똑같이 state를 관리하는 hook이지만 그 차이점은 복잡도에 있다고 생각한다. 특정 조건에 따라 여러개의 state가 바뀐다면 각각의 state를 useState로 관리하는게 아닌 useReducer를 통해 action type으로 구분하고 관리하는게 훨씬 간편하다고 느꼈다.