Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kendrelaxman/5a23f3813879ca6be4bfe39921a63f54 to your computer and use it in GitHub Desktop.
Save kendrelaxman/5a23f3813879ca6be4bfe39921a63f54 to your computer and use it in GitHub Desktop.
//To share a React context between multiple npm packages, you can create a new package that exports the context provider and consumer components. Then, you can import and use these components in each of the other packages that need to access the shared context.
//Create a new package called "shared-context" that exports the context and its provider and consumer components.
// shared-context/index.js
import React from 'react';
const SharedContext = React.createContext();
export const SharedProvider = SharedContext.Provider;
export const SharedConsumer = SharedContext.Consumer;
//In each of the other packages that need to access the shared context, import the provider and consumer components from the "shared-context" package and use them in the appropriate components.
// package-a/index.js
import React from 'react';
import { SharedProvider } from 'shared-context';
function PackageA() {
return (
<SharedProvider value={someValue}>
{/* other components here */}
</SharedProvider>
);
}
// package-b/index.js
import React from 'react';
import { SharedConsumer } from 'shared-context';
function PackageB() {
return (
<SharedConsumer>
{value => /* render something with the shared value */}
</SharedConsumer>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment