-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Add custom hook for context to avoid assertions #604
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
Conversation
abb61ac
to
73b3d95
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Definitely agree.
I would elaborate on different patterns though (don't we already have such a section?):
- runtime type checks
- static type assertions
Hey @eps1lon! I gave reworking the entire context page a try. I think the page is containing way too many not recommended patterns and unpractical examples that don't belong in the basic cheatsheet. I think providing recommended patterns for some common use cases together with some alternative patterns is a better approach. Patterns like context getters might fit in the advanced cheatsheet, but they would still require some rework. The suggested page is based on examples and recommendations from the new React docs. What do you think? |
README.md
Outdated
|
||
const Context = createContext({} as ProviderStore); // type assertion on empty object | ||
##### Type assertion as an alternative (not recommended) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Let's not do this for now. There are instances where type assertions are better (since they have no runtime impact) but it's on a case-by-case basis.
The rest is perfect. Nice job 👍🏻
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do you mean let's remove the "(not recommended)" part?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah. Though I think we should help somewhat in guiding. So maybe downgrade it from the heading to a paragraph like "when you don't know which to chose, use runtime checking and throwing".
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Added this in the end now:
When you don't know what to choose, prefer runtime checking and throwing over type asserting.
I'd like to avoid adding assertions and excessive
undefined
/null
checks. I generally use this approach and I think it can be considered a pretty widely spread good practice.