S
S
Sergey Chazov2020-05-06 10:20:36
React
Sergey Chazov, 2020-05-06 10:20:36

How to refer to a context that does not have a name?

Trying to study the topic of hooks, I ran into a misunderstanding. When I used hoc, I declared the context like this:

const {
    Provider: CompaniesStoreServiceProvider,
    Consumer: CompaniesStoreServiceConsumer
      } = React.createContext();


And in all the examples with hooks, I see that the context is declared as const myContext = React.createContext();

and then it is accessed useContext('myContext');

Can I, without changing my way of creating a context, access it through the useContext hook?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
ned4ded, 2020-05-06
@chazovs

No.
In useContext() , you need to pass a reference to the context object that you did not save. In js, undeclared objects cannot be accessed. Moreover, as soon as the object reference is not used, the object itself is removed by the garbage collector.

const MyContext = React.createContext();

const {
    Provider: CompaniesStoreServiceProvider,
    Consumer: CompaniesStoreServiceConsumer
} = MyContext;

useContext(MyContext);

Alternatively, you can make a helper/decorator that will create a context and return an object containing a reference to the context, the provider, and the consumer; destructure it already.

P
Pavel Didenko, 2020-05-06
@Dasslier

Export the variables CompaniesStoreServiceProvider, CompaniesStoreServiceConsumer. You wrap the application in a Provider, then wrap it in a Consumer wherever you need to and get the data from the props

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question