@lfades/atom

Straightforward state management for React

counter.tsx
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>
	)
}
0

Simple by design

@lfades/atom focuses on simplicity and React's principles

Minimal API

The entire source code is less than 100 lines long. Feel free to copy the code into your project instead of installing the package.

No Store

There's no underlying store or use of React Context. It's just a shared useState.

Less is More

React can do what a state management library does. You don't need anything more than just a shared value.

Installation

Install the package with your package manager of choice

pnpm add @lfades/atom

API Reference

A complete reference to the @lfades/atom API

atom

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(); // 1
useAtom

Returns 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);
useSubscribe

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]
);
useHydrate

Allows you to hydrate atoms, useful for updating atoms with data from the server.

// atoms-context.tsx
import { atom, useHydrate } from '@lfades/atom';

const atoms = { counterAtom: atom(0) };
export const atomsContext = React.createContext(atoms);

export function AtomsProvider({ children, data }) {
  useHydrate(() => {
    if (data) {
      atoms.counterAtom.set(data.counter);
    }
  }, [data]);

  return (
    <atomsContext.Provider value={atoms}>
      {children}
    </atomsContext.Provider>
  );
}

FAQ