Scopes are ideal for managing state that should survive for the lifecycle of a specific component, such as a form. By creating a scope for every form and making molecules depend on that scope, a new instance of the molecules is created for each unique scope instance.
Workflow:
- Create a scope object: Use
createScope to define the scope. - Depend on the scope in molecules: Inside a
molecule definition, call scope(yourScope) to make the molecule scoped. This ensures the state (e.g., a nanostore or Jotai atom) is unique to that scope. - Provide the scope: Use
provideScope at the top level of your form component tree. - Consume the molecule: Use
useMolecule in child components to access the scoped state.
import { createScope } from "bunshi";
// 1. Create scope
export const formScope = createScope<unknown>(undefined);
import { molecule } from "bunshi";
import { atom } from "nanostores";
// 2. Depend on scope in a molecule
export const FormErrors = molecule((mol, scope) => {
// Calling `scope` makes `FormErrors` a *scoped* molecule
scope(formScope);
const errors = atom<string[]>([]);
function addError(error: string) {
errors.set([...errors.get(), error]);
}
return {
addError,
errors,
};
});