Paul Henschel recently released jōtai, a new state management library for React. Jōtai claims a minimalistic API (three functions), TypeScript-readiness, and compatibility with React Suspense and Concurrent Mode.

Pieces of state that are not dependent on any other pieces of state can be created by passing an initial value to jōtai’s atom factory function. These independent pieces of state can then be composed into derived pieces of state with the same factory function, this time passing a function that computes the derived atom from its dependencies:

const count1 = atom(1)
const count2 = atom(2)
const count3 = atom(3)

const sum = atom(get => get(count1) + get(count2) + get(count3))

The atom factory function can be used to define in-place reducers, i.e. functions that update a piece of state from some argument parameter:

const decrementCountAtom = atom(
  get => get(countAtom),
  (get, set, _arg) => set(countAtom, get(countAtom) - 1),
)

function Counter() {
  const [count, decrement] = useAtom(decrementCountAtom)
  return (
    <h1>
      {count}
      <button onClick={decrement}>Decrease</button>
  )
}    

The atom factory function also allows developers to define actions, that is, procedures that may execute effects — and update relevant pieces of state. Actions may be asynchronous:

const fetchCountAtom = atom(
  get => get(countAtom),
  async (_get, set, url) => {
    const response = await fetch(url)
    set(countAtom, (await response.json()).count)
  }
)

function Controls() {
  const [count, compute] = useAtom(fetchCountAtom)
  return <button onClick={() => compute("http://count.host.com")}>compute</button>

#javascript #javascript libraries #web development #react #development #news

Jotai, a New Granular State Management Library for React
12.95 GEEK