React: Question: Can the useContext hook be used without a provider?

Created on 26 Jan 2020  路  1Comment  路  Source: facebook/react

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?

Invalid Question

Most helpful comment

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 defaultValue argument 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.

>All comments

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 defaultValue argument 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.

Was this page helpful?
0 / 5 - 0 ratings