I've been out of the frontend js scene for a while, and now try to catch up on React etc.
I don't really get contexts. First you need to create a context somewhere, then you can use <Context.Provider> <Child/> </Context.Provider>
, and then you need to dig the reference to the created context instance in <Child>
to use it. And I guess there are <Context.Consumer>
components also.
Why would i not just have a globalcontext.ts
where i put some variables and methods, and then just import it where I need those? Am I missing something?
It's hard to tell if your question is "why would I want to use Context instead of global variables/state," or "why is the usage more complicated than I think it should be."
Context lets you provide some scoped state that is:
The docs do an excellent job of explaining this.
As far as it seeming overly complicated, you need two things:
useContext
or the <Consumer/>
component, depending on the paradigm.I think both things are necessary to make the system work, and it can't be simpler that it must be.