React.useReducer()

BlackBean·2023년 11월 30일

React

목록 보기
1/6

Reducer란?

언제 사용할까

컴포넌트의 규모가 커지면, 한번에 컴포넌트의 state를 것을 관리하기 힘들어진다. reducer를 통해 여러 상태의 값을 하나의 함수로 관리할 수 있게 된다.

  • 여러 이벤트 핸들러에서 setState 로직을 사용할 때 사용하면 좋다
  • 방금 언급한 여러 이벤트 핸들러에서 useState 를 사용하는 케이스에서는 reducer 를 사용하면 디버깅하기 좋다.
  • useState 로 인한 버그가 많으면 reducer 를 사용해보길 추천!

useState를 useReducer로 변환하는 방법

1. setState 를 dispatching action 으로 옮긴다.

state를 사용할 때는 'what to do'에 의해 state를 설정하지만, action 을 dispatching할 때는 'what the user just did'로 설정한다. 다시 말하자면 기존에 setState를 하던 방법 대신에 action 을 dispatching 하면 된다.
참고로 action 객체는 어떤 형태여도 상관없지만 type 프로토타입은 string으로 사용하는 것이 일반적이다.

dispatch({
  // specific to component
  type: 'what_happened',
  // other fields go here
});

2. reducer 함수를 작성한다.

reducer 함수는 state 를 저장하는 로직이 있는 곳이다. currentState와 action object 를 받는다. 그리고 다음 state 를 리턴한다. React 는 리턴받은 state 를 현재 값으로 설정하게 된다.
reducer 가 함수 인자로 state를 받아오기 때문에 reducer 는 컴포넌트 밖에 선언해도 괜찮다. 밖에 선언한다면, 코드의 indent 가 줄어 읽기 더 편할 것이다.
참고로 reducer함수는 pure function 이다. reducer 는 state update 와 마찬가지로 rendering 하는 동안 동작한다. reducer는 pure 해야 한다(같은 input 에 대해 같은 output 이 나와야 함). request 를 보내거나 timer scheduling을 하거나, component 외의 부분을 동작시키는 일을 해서 안된다.

3. 컴포넌트 안에서 useState 대신 useReducer 를 사용한다.

import { useReducer } from 'react';
const [stateValues, dispatch] = useReducer(reducerFunction, initialValues);

참고

https://react.dev/learn/extracting-state-logic-into-a-reducer

profile
React, React-native, Web developer

0개의 댓글