-
Notifications
You must be signed in to change notification settings - Fork 47.3k
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
Feature Request: Add Warning when consuming a context whose provider is not mounted #20003
Comments
This is definitely a pain point |
@jonrose-dev You can overcome that problem by following this pattern shown by Kent C Dodds. I found it so useful.
You can see the full article here |
FWIW reading a value from an unmounted context is a supported use case. (The context API supports a default value for this purpose.) For example, a UI library might export a theme context that allows you to override the component themes if you want or use the default theme if you don't. Edit Maybe we could add a DEV warning only for contexts where |
@Satsh24 I'm actually using a similar pattern with the exception of the check for |
@jonrose-dev, I accidentally clicked the edit button on your comment rather than mine to add the "edit" footnote. Sorry! It popped in under my comment and I guess I'm just not very good at GitHub still 😆 |
@bvaughn interesting point I hadn't considered. I'd still love to see some sort of feedback telling me my Provider hasn't mounted when I attempt to use the context. Not sure if there is a best path forward then on this |
lol no worries. I was confused at first but then figured it out 😆 |
Well I mentioned above that maybe we could add a DEV warning only if the context was created without a default value (aka |
That would be helpful for those using JS and don't get the type checking for Though this may not solve my specific problem (I use TS but just forget to mount the provider), I do agree it'd be helpful. I'd like to take a crack at the PR to add the warning |
I quote the suggestion of a warning as in my experience it's hard to convince a team of the need for a safe check for missing provider. I did write one and a war started in my team on the reasons why I implemented it 🤣. |
We intentionally don't do this because in many cases it's completely legit. In cases where it's not, you're welcome to implement this in userland. E.g. you can make some context |
React allows you to consume a
context
, even if it'sProvider
is not mounted. Imagine a scenario where you are building a new context, and forget to add theProvider
. When you consume it with eitheruseContext
or theConsumer
component, React will run without issue, but your code won't work as expected. This has led to hours of lost time debugging the wrong problem. Adding a warning that a context is being consumed that does not have itsProvider
mounted, would help to reduce the time spent debugging this issue.The text was updated successfully, but these errors were encountered: