react-singularity
v0.2.0
Published
Ascetic shared state management library for React.
Downloads
2
Readme
react-singularity
Ascetic shared state management library for React.
⚠ Work in progress, nothing to see here now :)
Setup
npm i react-singularity
At the moment this library does not have React in dependencies, but relies on useSyncExternalStore hook (React 18+). You should pass it explicitly to create atom factory:
import { createAtomFactory, createSingularityFactory } from 'react-singularity';
export const atom = createAtomFactory({ useSyncExternalStore });
export const singularity = createSingularityFactory({ useSyncExternalStore });
Atom
Atom is a primitive store with use
and set
methods.
const $count = atom(0);
const Component = () => {
const onClick = useCallback(() => {
$count.set((c) => c + 1);
}, []);
const count = $count.use();
return <div onClick={onClick}>{count}</div>;
};
(atom also has get
and subscribe
methods for advanced usage, see implementation).
Singularity
Singularity is a set of atoms of the same type.
const $colors = singularity(() => '#FFFFFF');
const Pixel = ({ x, y }) => {
const key = `${x},${y}`;
const onClick = useCallback(() => {
$colors.set(key, () => '#000000');
}, []);
const color = $colors.use(key);
return <div style={{ background: color }} className="pixel" onClick={onClick} />;
};
Credits
This project was bootstrapped with TSDX.