How to share context between different component libraries in react?

Viewed 1014

In react there's an easy way to share "information" within several layers of components. This is by using context

import {UserCtx} from "./stores/UserCtx"; 
<UserCtx.Provider value={new user(info)}>
    <SomeComponent />
</UserCtx.Provider/>

And then in some component:

import {UserCtx} from "./stores/UserCtx";
function SomeComponent() {
    const userData = React.useContext(UserCtx);
    return <div>JSON.stringify(userData)</div>
}

However this requires the context object definition to be visible for all objects. And thus when creating a library of components it cannot really be used?

Say in above "example" SomeComponent would be a library component, how would I share the context of the main application to the component? Sharing by adding an attribute seems far fetched, at that point I might as well just provide the user (or whatever the context stores) directly?

2 Answers

All your library of components should be children of the component where value is generated. That is, if your component is the main component exposed to the DOM, value should come there at that top so that any of the components can consume the context.

Mind you, context is wonderful to help you avoid drilling of your components. If you need more flexibility than this, Redux may give you more power.

Let's say we have 3 things:

  1. the main project which include the module where the context provider is, and the module where the component library is
  2. the context provider module
  3. the component library project

To make the main project and the component library project share the same context provider, you have not to add the context provider module as a dependency into you component library project but as a dev dependency

Related