Search code examples
reactjsreact-context

Why do I need a fancy jsx syntax for React Contexts


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?


Solution

  • 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:

    1. readable from within the components that are wrapped by the context provider
    2. broader than props
    3. more tightly scoped than global variables
    4. reactive (IE the children that read the context will re-render when it changes.) Simply exporting values or method from a module won't give you this.

    The docs do an excellent job of explaining this.

    As far as it seeming overly complicated, you need two things:

    1. A source and boundary for the context. That's the provider.
    2. A method to read from the context. That's 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.