Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement the createContext hook #1354

Closed
sungik-choi opened this issue May 16, 2023 · 0 comments · Fixed by #1442
Closed

Implement the createContext hook #1354

sungik-choi opened this issue May 16, 2023 · 0 comments · Fixed by #1442
Assignees
Labels
refactoring Issue or PR related to refactoring with no functional changes

Comments

@sungik-choi
Copy link
Contributor

sungik-choi commented May 16, 2023

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

@sungik-choi sungik-choi added the refactoring Issue or PR related to refactoring with no functional changes label May 16, 2023
@sungik-choi sungik-choi self-assigned this May 16, 2023
@sungik-choi sungik-choi added the good first issue Issue that good for newcomers label Jun 22, 2023
@sungik-choi sungik-choi self-assigned this Jun 23, 2023
@sungik-choi sungik-choi removed the good first issue Issue that good for newcomers label Jun 30, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
refactoring Issue or PR related to refactoring with no functional changes
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant