11-1. Basic
- 다양한 컴포넌트의 state를 업데이트 할 때 사용하는 hook
- 가장 큰 장점은 컴포넌트 업데이트 로직을 컴포넌트 밖으로 분리 가능
- 리듀서는 새로운 상태를 만들 때 반드시 불변성을 지켜주어야 함(기존 state의 값을 변경하는 것이 아니라 새롭게 생성)
const {useReducer} = React;
function reducer(state, action){
switch(action.type){
case 'INCREMENT' :
return { value : state.value + 1 };
case 'DECREMENT' :
return{ value : state.value - 1 };
default :
return state;
}
}
function Counter(){
const [state, dispatcher] = useReducer(reducer,{ value : 0 });
console.log(useReducer(reducer, {value : 0}));
return (
<>
<h1>count : {state.value} </h1>
<button
onClick = {() => dispatcher({ type : 'DECREMENT'})}
> -1 </button>
<button
onClick = {() => dispatcher({ type : 'INCREMENT'})}
> +1 </button>
</>
);
}
ReactDOM.createRoot(document.getElementById('root')).render(<Counter/>);
- 리듀서를 이용해 input 입력 값 상태 관리
const {useReducer} = React;
function reducer(state, action){
return ({
...state,
[action.name] : action.value
});
}
function RegistForm(){
const [state, dispatcher] = useReducer(reducer,{
name : '',
nickname : ''
});
const { name, nickname } = state;
const onChangeHandler = e => dispatcher(e.target);
return (
<>
<label>이름 : </label>
<input type="text" name="name" value={name} onChange = { onChangeHandler }/><br/>
<label>닉네임 : </label>
<input type="text"name="nickname" value={nickname} onChange = { onChangeHandler }/><br/>
<h3> 입력한 이름 : {name}</h3>
<h3> 입력한 닉네임 : {nickname}</h3>
</>
)
}
ReactDOM.createRoot(document.getElementById('root')).render(<RegistForm/>);