score:-1

should your code of consumer be

      <React.Fragment>
        <MyContext.Consumer>
          {value => /* render something based on the context value */}
        </MyContext.Consumer>
      </React.Fragment>

as stated from the official react doc : https://zh-hant.reactjs.org/docs/context.html

when you define

enter image description here

you can use it like

enter image description here

score:0

Apart from Darko's answer, esm and cjs export is also a possible reason for context to fail in a package. If you use the hook in esm and the provider in cjs, you will not get the value for that context.

score:0

I recently had a similar issue where I was trying to consume the value of a context inside my library components but using the provider (imported from the package) in the host app.

I managed to solve the issue just by making react and react-dom external and peerDependencies when bundling in rollup.

score:9

Maybe you are making multiple instances of the component providing the context. Let's say you have a component Sound, which starts by:

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

If you import this library from your main project, the context will be created at the global space. You then use it to render your document tree. But in another component you also imported this library, which had to be resolved during webpack transpilation. It thus has its own copy of the above lines and a context object created in its own space. The problem occurs when you try to use the Consumer, because the Provider was only made by the main project for the first context object, and the second context's provider instance was never instantiated, thus returns undefined.

A solution to the problem is to enforce a single context object, which you can achieve by telling the second component's webpack that the provider-owning library is an external, so when webpack reaches e.g. the "import sound" line, it will not go further and will assume this dependency is resolved at runtime. When runtime comes, it will take it from the same place where the main project is taking it. To do this in webpack, e.g. for above "sound" library, add this to your other component (not main project):

{
   ...
   externals: {
      ...
      'sound': 'sound'
   }
   ...
}

Also in your component package.json:

{
   ...
   peerDependencies: {
     "sound": "^1.2.3"
   }
}

Related Query

More Query from same tag