Is React context supposed to always be a singleton, or is there another way?
Asked Answered
M

2

5

Every example I've seen of React context is like this:

theme-context.js

// Make sure the shape of the default value passed to
// createContext matches the shape that the consumers expect!
export const ThemeContext = React.createContext({
  theme: themes.dark,
  toggleTheme: () => {},
});

Where you're having a file contain an instance of the context. Then you pass it into the component using useContext(ThemeContext).

My question is, if you're doing this and it's always a singleton, why don't you simply just import the stuff in the context directly from the singleton so to speak. Basically I'm wondering if there is ever a time where you create more than one instance of your context, such as perhaps for testing you create a new one per test, something like that.

Monochromat answered 20/7, 2019 at 9:6 Comment(0)
F
1

I also came across this question myself. (If I understand the question correctly)

And I think you may misunderstand that the useContext is singleton instance, Which I did but I just try it out and it's allow me to use multiple instances of the same context.

So basically const ContextA = createContext({}) is for create a type reference not a data instance.

And using ContextA.Provider (the provider) is to an actual data instance. And you can use as many provider you want.

The reason we need singleton context (createContext) is because js doesn't have type, So we can't query any target provider using a type

Flawed answered 17/6, 2022 at 1:24 Comment(0)
A
-3

First of all, the value in React.createContext({'light'}) is default. It is mostly used for debug or just skip it, and leave it empty React.createContext(). Example of usage: You have a data in your Context.Provider, but you are not sure, if you passed it right to your Product.Consumer, so if the default value pops out, you know that you did something wrong.

In documention such technique is used to pass simple data, like singletone React.createContext({'theme:themes.dark'}).

In most cases, you will use Context.Provider and Context.Consumer, or even pass through this.context.

Documentation strictly explained every details, try search for Context.Provider, Class.contextType, Context.Consumer in documentation.

Altercate answered 20/7, 2019 at 12:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.