@lfades/atom
Straightforward state management for React
import { atom, useAtom } from "@lfades/atom"
const counterAtom = atom(0)
function Counter({ props }: Props) {
const [count, setCount] = useAtom(counterAtom)
const increment = () => setCount(count + 1)
const decrement = () => setCount(count - 1)
return (
<div className="flex flex-col items-center gap-4">
<div className="text-4xl font-bold">{count}</div>
<div className="flex gap-2">
<button onClick={decrement}>-</button>
<button onClick={increment}>+</button>
</div>
</div>
)
}Simple by design
Minimal API with no store, built around React's principles.
The entire source code is just 65 lines long. Feel free to copy the code into your project instead of installing the package.
atom does not have a underlying store or context, but it integrates easily with one when needed, and it encourages updates to happen inside React components instead of a library API.
Installation
Install the package with your package manager of choice
pnpm add @lfades/atomOr just copy the code.
API Reference
A complete reference to the @lfades/atom API
Creates an atom with a given initial value.
import { atom } from '@lfades/atom';
const counterAtom = atom(0);
// Read the value
counterAtom.get(); // 0
// Update the value
counterAtom.set(1);
counterAtom.get(); // 1Returns the current value of the atom and a setter function to update it. This also subscribes the component to the atom, so it will re-render when the atom value changes.
import { useAtom } from '@lfades/atom';
const [count, setCount] = useAtom(counterAtom);
// ..
setCount(1);
setCount === counterAtom.set; // true
// Creating an atom inside a component
const localAtom = useMemo(() => atom(0), []);
const [localCount, setLocalCount] = useAtom(localAtom);Subscribes to the atom and calls the callback function with the new value whenever it changes.
import { useSubscribe } from '@lfades/atom';
useSubscribe(counterAtom, (value) => {
console.log(value);
});
// With dependencies
useSubscribe(
counterAtom,
(value) => {
console.log(value, dep);
},
[dep]
);Advanced patterns
Pick the setup that matches your app: a shared provider for many atoms, or a single-atom context.