Skip to content
Bunshi
GitHub

molecule

molecule<T>(construct): Molecule< T >

Create a new molecule

Molecules are the core building block of bunshi. They are functions that return a value. Molecules can depend on other molecules. When molecules depend on other molecules, anything that they depend on will be automatically created.

Molecules can also depend on scopes. When a molecule depends on a scope, then an instance will be created for each scope. In other words, your molecule function will be run once per unique scope, instead of once globally for your application.

Rules of molecules:

  • A molecule without any dependencies or scopes will only be called once.
  • A molecule that depends on scope (a scoped molecule) will be called once per unique scope.
  • A molecule that depends on a scoped molecule will be called once per unique scope of it’s dependency.
  • If a molecule calls scope then it will be a scoped molecule.
  • If a molecule calls mol then it will depend on that molecule.

Create a global molecule

const globalMolecule = molecule(()=>Math.random());

Create a dependent molecule

const dependentMolecule = molecule(()=>`My dependency: ${use(globalMolecule)}`);
const dependentMolecule = molecule((mol)=>`My dependency: ${mol(globalMolecule)}`);

Create a scoped molecule

const formScopedMolecule = molecule(()=>use(formScope));
const formScopedMolecule = molecule((_,scope)=>scope(formScope));
```*

## Type parameters

| Parameter |
| :------ |
| `T` |

## Parameters

| Parameter | Type | Description |
| :------ | :------ | :------ |
| `construct` | [`MoleculeConstructor`](/reference/react/type-aliases/type-aliasmoleculeconstructor/)\< `T` \> | A callback function called to create molecule instances |

## Returns

[`Molecule`](/reference/react/type-aliases/type-aliasmolecule/)\< `T` \>

a molecule

## Source

[src/vanilla/molecule.ts:116](https://github.com/saasquatch/bunshi/blob/8a68ffe/src/vanilla/molecule.ts#L116)