I wonder if I can have multiple <Context.Provider/>
to provide the value for a Context
. I'd like to have multiple components (the contents of various pages) provide values such as the page title to a topbar.
Is it possible? Thanks
Asked
Active
Viewed 440 times
-1

Drew Reese
- 165,259
- 14
- 153
- 181

JavierG
- 201
- 4
- 12
-
1Yes, but each consumer will only get the value from a single provider (the nearest provider up the component tree). – Nicholas Tower Jun 24 '22 at 17:30
-
1Why can't you store it in the single context? – Joel Hager Jun 24 '22 at 17:31
-
@NicholasTower Thanks, so in my case it would work? I mean, I have only one consumer, my topbar – JavierG Jun 24 '22 at 17:34
-
@JoelHager well I should have multiple providers for that to work, right? Could you please give me an example on what you mean? I'm not sure I'm understanding it right – JavierG Jun 24 '22 at 17:37
-
1@JavierG it doesn't sound like it will work. It sounds like you want your topbar to get data from *multiple* sources. It can only read from one. – Nicholas Tower Jun 24 '22 at 17:38
-
@NicholasTower thanks, so I could simply have a global variable atrached to the window object and read and write values there? I don't want to use fancy frameworks like Redux for this – JavierG Jun 24 '22 at 17:41
-
1Does something like this help answer your question? https://stackoverflow.com/a/68640880/8690857 Or are you really just asking if you can use more than one React context (i.e. different contexts)? – Drew Reese Jun 24 '22 at 17:52
-
1You just store multiple values or functions / reducers in your single store. – Joel Hager Jun 24 '22 at 20:31
-
@DrewReese thanks but no, I don't think that would answer my question – JavierG Jun 24 '22 at 21:22
-
1Right, so it wasn't clear if you want to use multiples of the same context provider, or if you are wanting to use several *different* providers. Though I'm rereading your post again now and sounds like you want to use several of the same provider, in several places providing to *different* ReactSubTrees. A [mcve] for what you are trying to do would probably be helpful here. – Drew Reese Jun 24 '22 at 21:25
1 Answers
1
You can make multiple but it will affect one context so if you need multiple functionalities you can implement them in one context and use them by destructuring
<DemoContext.Provider value={{function1, function2 function3}}></DemoContext.Provider>
use
const {function1}= useContext(DemoContext)

Nipu Chakraborty
- 9
- 3