컴포넌트의 규모가 커지면, 한번에 컴포넌트의 state를 것을 관리하기 힘들어진다. reducer를 통해 여러 상태의 값을 하나의 함수로 관리할 수 있게 된다.
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
});
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 외의 부분을 동작시키는 일을 해서 안된다.
import { useReducer } from 'react';
const [stateValues, dispatch] = useReducer(reducerFunction, initialValues);
https://react.dev/learn/extracting-state-logic-into-a-reducer