React Hook 중에서 컴포넌트의 상태를 업데이트 할 때 사용하는 Hook으로는 useState와 useReducer가 있다.
useReducer를 중심해서 두가지 Hook의 차이점에 대해 간단히 정리해보고자 한다.
1. useState
- 설정하고 싶은 다음 상태를 직접 지정해주는 방식으로 상태를 업데이트 해준다.
- useState를 통해 변수를 만들고 화면을 렌더링 시키면, set함수를 통해 바뀐 데이터만 React DOM에 리렌더링이 되도록 해준다.
- 이러한 방식으로 불변성을 유지하며 변수의 상태를 업데이트 시키기 위한 Hook이다.
2. useReducer
- action 객체를 기반으로 상태를 업데이트 해준다(action 객체: 업데이트 할 때 참조하는 객체)
- 보통 type(변수명, 변경가능) 이라는 값을 사용해서 어떤 업데이트를 할지 명시해준다.
dispatch({
type: 'CHANGE_INPUT',
name,
value
})
- 컴포넌트 상태 업데이트 로직을 컴포넌트로부터 분리가 가능하다.
- 심지어 다른 파일에 작성 후 불러올 수도 있다.
함수명 | 기능 | 기타 |
reducer | 상태를 업데이트 하는 함수 | |
function reducer(state, action) {
switch (action.type) {
case 'CHANGE_INPUT':
return {
...state,
inputs: {
...state.inputs,
[action.name]: action.value
}
};
case 'CREATE_USER':
return {
inputs: initialState.inputs,
users: state.users.concat(action.user)
};
case 'REMOVE_USER':
return {
...state,
users: state.users.filter(user => user.id !== action.id)
}
default:
throw new Error('Unhandled action');
}
}
3. useReducer 사용 방법
const [state, dispatch] = useReducer(reducer, initialState);
더보기
Parameter
reducer: 컴포넌트에 사용할 reducer 함수
initialState: 기본값
state: 현재 상태
dispatch: 액션을 발생시키는 함수
#예제1
const initialState = {
inputs: {
username: '',
email: '',
},
users: [
{
id: 1,
username: 'rupnajane',
email: 'public.rupnajane@gmail.com',
active: true,
},
{
id: 2,
username: 'tester',
email: 'tester@example.com',
active: false,
},
{
id: 3,
username: 'lake',
email: 'lake@example.com',
active: false,
}
]
}
function reducer(state, action) {
switch (action.type) {
case 'CHANGE_INPUT':
return {
...state,
inputs: {
...state.inputs,
[action.name]: action.value
}
};
case 'CREATE_USER':
return {
inputs: initialState.inputs,
users: state.users.concat(action.user)
};
case 'REMOVE_USER':
return {
...state,
users: state.users.filter(user => user.id !== action.id)
}
default:
throw new Error('Unhandled action');
}
}
function App() {
const [state, dispatch] = useReducer(reducer, initialState);
const nextId = useRef(4);
const { users } = state;
const { username, email } = state.inputs;
const onChange = useCallback(e => {
const { name, value } = e.target;
dispatch({
type: 'CHANGE_INPUT',
name,
value
})
}, []);
const onCreate = useCallback(() => {
dispatch({
type: 'CREATE_USER',
user: {
id: nextId.current,
username,
email,
}
})
nextId.current += 1;
}, [username, email]);
const onRemove = useCallback(id => {
dispatch({
type: 'REMOVE_USER',
id
});
}, []);
https://react.vlpt.us/ 강의자료를 참고하여 작성하였습니다.
'react.js' 카테고리의 다른 글
React에서 중요하게 알아야 할 몇가지 개념 정리 (0) | 2021.10.06 |
---|---|
useRef 사용법 정리 (2) | 2021.07.02 |
React 기록 시작 (0) | 2021.06.09 |