Is it a correct form to use the useContext hook without the enclosing provider?
See this simple sandbox which uses the JediContext.Provider.
In this modified sandbox I removed the provider and the useContext hook still works.
What are the consequences of using the useContext hook without a provider?
I don't think this is a question about the useContext hook so much as it is a question about the Context API and it's default value behavior. For that I suggest checking out the Context page:
https://reactjs.org/docs/context.html
Specifically, this section:
The
defaultValueargument is only used when a component does not have a matching Provider above it in the tree. This can be helpful for testing components in isolation without wrapping them.
In addition to being useful for testing, default value can also be useful for shared components that want to implement a default behavior but allow it to be overridden or configured.
Consider the following example app:
const ExampleContext = React.createContext("foo");
function ExampleComponent() {
const value = React.useContext(ExampleContext);
return <div>value is {value}</div>;
}
<React.Fragment>
<ExampleComponent />
<ExampleContext.Provider value="bar">
<ExampleComponent />
</ExampleContext.Provider>
</React.Fragment>;
The first ExampleComponent would read the default "foo" value, and the second would read the overridden "bar" value.
Most helpful comment
I don't think this is a question about the
useContexthook so much as it is a question about the Context API and it's default value behavior. For that I suggest checking out the Context page:https://reactjs.org/docs/context.html
Specifically, this section:
In addition to being useful for testing, default value can also be useful for shared components that want to implement a default behavior but allow it to be overridden or configured.
Consider the following example app:
The first
ExampleComponentwould read the default "foo" value, and the second would read the overridden "bar" value.