triple-frontend icon indicating copy to clipboard operation
triple-frontend copied to clipboard

[react-contexts] context의 provider가 없으면 에러 처리하기

Open drakang4 opened this issue 3 years ago • 1 comments

as-is

const someContext = createContext<ContextValue>({
  stringValue: '',
  functionValue: noop,
})

function useSomeContext() {
  const context = useContext(someContext)
  return context
}

to-be

const someContext = createContext<ContextValue | undefined>(undefined)

function useSomeContext() {
  const context = useContext(someContext)
  if (context === undefined) {
    throw new Error('SomeProvider is required.')
  }
  return context
}

react-contexts 모듈에서 createContext API로 컨텍스트 객체를 생성할 때 defaultValue를 정의하고 있습니다. 타입 에러를 피하기 위해 정의한 듯 한데 defaultValue는 컴포넌트 상위 트리에 Provider가 존재하지 않는 상황에만 쓰입니다. 하지만 대부분은 불필요한 경우입니다.

필수로 Provider에 값을 전달해야 하는 컨텍스트는 빈 스트링이나 noop 함수 같은 의미 없는 기본 값을 defaultValue로 정의할 필요가 없습니다. 대신 hook에서 예외 처리를 통해 컨텍스트의 타입을 보장할 수 있습니다.

drakang4 avatar Sep 30 '21 09:09 drakang4