Skip to content

Implement the createContext hook #1354

@sungik-choi

Description

@sungik-choi

Description

Reasons for suggestion

리팩토링

Proposed solution

function createContext<ContextValue>(
  providerName: string,
  defaultValue: ContextValue,
) {
  const Context = React.createContext<ContextValue>(defaultValue)

  function useContext(consumerName: string) {
    const contextValue = React.useContext(Context)

    if (!contextValue) {
      throw new Error(`'${consumerName}' must be used within '${providerName}'`)
    }

    return contextValue
  }

  return [
    Context.Provider,
    useContext,
  ] as const
}
  • 초기 구현
  • FormControl 의 케이스처럼, 해당하는 컨텍스트 프로바이더 내부에 위치하지 않더라도 잘 동작해야하는 케이스에선 에러를 던져선 안됨
  • 개선 방법 고민 필요
    • FormControlContext 의 경우엔 예외로, 컨텍스트의 기본값을 nullish한 값으로 설정하지 않는 방법

References

Metadata

Metadata

Assignees

Labels

refactoringIssue or PR related to refactoring with no functional changes

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions