Keep your components independent and reusable by using component-level state management to store data that is specific to a component.
When data needs to be shared across multiple components, we recommend using React Context over third-party state management libraries. This will make your components compatible with a wider range of host apps.
Run the following to create a context component:
Implement your Context component. For example:
Maintain different aspects of your global data in separate context components, to reduce centralization and improve your apps' maintainability and scalability.
For example, ThemeProvider
, UserAuthProvider
, UserLocaleProvider
, and so on.
Snap and export your component to its remote scope:
Run the following to create a component that will use the context component:
Use the custom hook provided by the context component, to access its data:
// @filename: greeter.tsx import { useUserLanguage } from '@learnbit-react/state-management.context.user-language'; export const Greeter = () => { const { language } = useUserLanguage(); if (language === 'en') return <h3>Hello!</h3>; return <h3>Hola!</h3>; };
Wrap your component's compositions with the context component:
// @filename: greeter.compositions.tsx
import { UserLanguageProvider } from '@learnbit-react/state-management.context.user-language';
import { Greeter } from './greeter';
export const BasicGreeter = () => {
return (
<UserLanguageProvider language="sp">
<Greeter />
</UserLanguageProvider>
);
};
Hola!
As a rule of thumb, context provider components should be configured as peer dependencies, to avoid multiple instances of the same provider in the same app or preview.
/* @filename: env.jsonc */ { "policy": { "peers": [ { "name": "@my-org/my-scope.context.user-language", "version": "0.0.1", "supportedRange": "^0.0.1" } ] } }
Avoid cyclic dependencies
Setting a component as a peer dependency of itself, or as a regular dependency of its env, will cause a cyclic dependency error. To prevent that, use a different env for your context providers.