reducer 를 인자로 받으면 상태 갱신 규칙을 훅 밖(호출자)으로 넘길 수 있다 — 넘긴 reducer 가 반환한 값이 곧 다음 state 라서, 기본 reducer 를 불러 그 결과를 반환하면 기본 동작이 유지된다.1

function toggleReducer(state, action) {
  switch (action.type) {
    default:
      return state
  }
}

function useToggle({ reducer = toggleReducer } = {}) {
  const [state, dispatch] = useReducer(reducer, {})
  return { state, dispatch }
}

export function Component() {
  useToggle({
    reducer(currentState, action) {
      console.log(currentState, action)
      return toggleReducer(currentState, action)
    },
  })
}

useReducer를 이용한 커스텀훅 사용에 대한 간단한 예시. 생각해보니 reducer를 전달해서 재사용하는 방법은 잘 생각못했는데 응용할 수 있을 것 같다.



Footnotes

  1. The State Reducer Pattern with React Hooks: “people can use our useToggle hook with their own reducer or they can use it with the built-in one.” ↩

  2. 리듀서를 사용하여 예측 가능하고 테스트 가능한 방식으로 상태 업데이트 및 작업을 캡슐화하는 방법과 State Reducer 패턴을 사용하여 이를 사용하는 구성 요소에서 상태 업데이트를 추상화하여 해당 구성 요소가 특정 기능에 더 집중하도록 만드는 방법을 설명. ↩

`#36`