State Management

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:

$bit
Copiedcopy

Implement your Context component. For example:

my-scope/context/user-language
index.ts
index.ts
use-user-language.ts
use-user-language.ts
user-language-context-provider.tsx
user-language-context-provider.tsx
user-language-context.composition.tsx
user-language-context.composition.tsx
user-language-context.tsx
user-language-context.tsx

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:

$bit
Copiedcopy
$bit
Copiedcopy

Using the context component

Run the following to create a component that will use the context component:

$bit
Copiedcopy

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>;
};
CopiedCopy

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>
  );
};
CopiedCopy

Hola!

Setting context providers as peer dependencies

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"
      }
    ]
  }
}
CopiedCopy
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.