jotai-molecules.
See Motivation for more details.
Install
What are Molecules?
Molecules are a pattern for creating scoped atoms that can depend on React props and context. They allow you to:- Create atoms that are scoped to a part of your component tree
- Pass props/context values to atom initialization
- Reuse the same atom definition in multiple places without sharing state
- Access parent scope atoms from child scopes
Usage Example
- Each
ScopeProvidercreates a separate instance of the count atom - Counters within the same scope share state
- Counters in different scopes have independent state
- The initial value comes from the scope
Key Concepts
Molecules
A molecule is a factory function that creates atoms. It receives two parameters:getMol: Function to get other moleculesgetScope: Function to get scope values (props/context)
Scopes
Scopes allow you to pass values (like props or context) to molecules. Create a scope withcreateScope() and provide values with ScopeProvider.
useMolecule
TheuseMolecule hook retrieves the atom instance for the current scope. It automatically handles scope boundaries and atom lifecycle.
Benefits
- Dependency Injection: Pass values to atoms without prop drilling
- Isolated State: Same atom definition, different state per scope
- Composition: Molecules can depend on other molecules
- Type Safety: Full TypeScript support