React.js
useReducer
coffee.
2024. 1. 30. 20:16
useReducer는 컴포넌트에 reducer를 추가하도록 하는 리액트 훅 입니다.
const [state,dispatch] = useReducer(reducer,initialArg,init?)
Reference
reducer로 state를 관리하기 위해 컴포넌트 상위에 useReducer를 호출하세요
파라미터
-reducer:어떻게 state가 update되는 지를 명시해놓은 reducer 함수입니다.
reducer의 파라미터는 state와 action을 가집니다. 그리고 다음 state를 리턴해야 합니다.
state와 action은 어떠한 타입도 가능합니다.
-initialArg:초기상태로 계산된 값,어떠한 타입도 가능
-(optional)init:초기화함수, 초기 state를 리턴합니다. 만약 정의되어 있지 않다면 초기값은 initialArg로 세팅됩니다.
그렇지 않으면 초기값은 init(initialArg)의 리턴값으로 세팅
Returns
useReducer는 두 값을 가진 배열을 리턴합니다.
1.현재의 state 첫 렌더링 시에 init(initialArg) 또는 initialArg로 세팅
2.dispatch 함수:state를 업데이트하고 리렌더링 됩니다.
예제
import { useReducer } from 'react';
function reducer(state, action){
if(action.type === 'incremented_age'){
return {
age:state.age +1
};
}
throw Error('Unknown action.');
}
function App() {
const [state, dispatch] = useReducer(reducer, {age:42});
return (
<div>
<button onClick = {
()=>{
dispatch({type:'incremented_age'});
}
}>Increment age</button>
<p>Hello! You are {state.age}</p>
</div>
);
}
export default App;