🚀 useReducer ?
- useState를 대체할 수 있는 함수
➡️ react에서 컴포넌트의 상태 관리를 위해 기본적으로 많이 쓰이는 hook은 state
- 좀 더 복잡한 상태관리가 필요한 경우
reducer
를 사용할 수 있음
➡️ 콜백대신 dispatch
함수를 전달할 수 있기 때문
reducer
는 이전 상태와 Action을 합쳐, 새로운 state를 만드는 조작
👥 Reducer를 사용하기 위한 구성요소
①. useReducer 함수
import React, {useReduser} from "react";
const ['상태', dispatch] = useReducer('reducer함수', initialState);
- 상태: 컴포넌트에서 사용할 상태
- dispatch: 첫번째 인자인 reducer함수를 실행시켜줌 ( 컴포넌트 내에서 상태의 업데이트를 일으키기 위해 호출)
- reducer함수: 컴포넌트 외부에서 상태를 업데이트 해주는 함수
- initialState: 초기상태
②. dispatch 함수
- Reducer함수를 실행시킴
- action 객체를 인자로 받음
action객체
dispatch({action:'updated', ...});
<button onClick={() => dispatch({ type: "INCREMENT" })}>
증가
</button>
- 어떤 행동인지를 나타내는 type 속성과 관련된 데이터(payload)를 담고 있음
➡️ action을 이용하여 컴포넌트 내에서 state의 업데이트를 일으킴
Couter 예시
const initialState = {count:0};
function reducer(state, action) {
switch(action.type) {
case 'increase': {
return {count: state.count +1};
case 'decrease': {
return {count: state.count -1};
default:
throw new Error();
}
}
import {useReducer} from 'react'
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return(
<>
count: {state.count}
<button onClick = {() => dispatch({action:'increase'})}>+</button>
<button onClick = {() => dispatch({action:'decrease'})}>-</button>
</>
);
}