본문 바로가기
front-end/React

[React] Hook: useReducer

by -제이리 2022. 8. 16.
728x90
320x100

 

useReducer란?

복잡한 상태 관리가 필요한 컴포넌트에 적합한 Hook이다. 

 

 


useReducer 함수

const [state, dispatch] = useReducer(reducer, initialState, init)

파라미터 설명

  • state: 컴포넌트에서 사용할 State(상태).
  • dispatch: reducer 함수를 실행시키며, 컴포넌트 내에서 state의 업데이트를 일으키기 위해서 사용하는 함수. 
  • reducer: 컴포넌트 외부에서 state를 업데이트하는 로직을 담당하는 함수. 현재의 state와 action 객체를 인자로 받아서, 기존의 state를 대체(replace)할 새로운 State를 반환(return)하는 함수.
  • initialState: 초기 값
  • init: 초기 함수

 

인자로 들어가는 함수

  • dispatch 함수: state 업데이트를 위한 요구전달
  • reducer함수: state를 업데이트 하는 역할

dispatch 함수

// ...
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
// ...

 

인자로 action객체가 들어온다. type속성과, 관련된 데이터를 담는다.

action객체에서 reducer함수에 요구하는 행동을 던지면 reduce함수는 action에 따라 상태(state)를 변경한다.


reducer 함수

function reducer(state, action) {
  switch (action.type) {
    case "decrement":
      return state - 1;
    case "increment":
      return state + 1;
    default:
      throw new Error("Unsupported action type:", action.type);
  }
}
 

파라미터 설명

  • state: 현재 상태값
  • action: dispatch함수에 들어간 객체

switch문이나 else if를 사용한다.

action을 전달받으면 상태를 변경해준다.

728x90
320x100

댓글