Skip to content
This repository has been archived by the owner on Jul 28, 2023. It is now read-only.

Child using React context throws when there is no parent that provides that context #46

Closed
luisherranz opened this issue Jul 26, 2022 · 2 comments · Fixed by #51
Closed
Labels
bug Something isn't working

Comments

@luisherranz
Copy link
Member

If you add a child block that is using a React context, but there is no parent block present to provide it, the hydration crashes.

At first, I thought it should be a matter of just checking if the provider is there and avoiding the error, but it's true that useContext needs to return something. So I'm not sure anymore what should happen here:

  • At least, we should provide a better error.
  • Maybe instead of erroring, we should pass null to useContext, although that may lead to errors in React that may be hard to debug.

I'm open to ideas 🙂🤷‍♂️

https://www.loom.com/share/8e965b18897a4fe58121a461898c6b42

@ockham
Copy link
Collaborator

ockham commented Aug 8, 2022

I think it would make sense if "our" useContext was consistent with React's and -- in the absence of a Provider -- returned the default value used when creating the context:

const MyContext = React.createContext(defaultValue);
[...]
The defaultValue argument is only used when a component does not have a matching Provider above it in the tree. This default value can be helpful for testing components in isolation without wrapping them. Note: passing undefined as a Provider value does not cause consuming components to use defaultValue.

(source)

@ockham
Copy link
Collaborator

ockham commented Aug 8, 2022

I'll file a PR for the above suggestion 😊

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants