2.0.0 • Published 5 months ago

react-atomic-state v2.0.0

Weekly downloads
32
License
MIT
Repository
github
Last release
5 months ago

⚛️ react-atomic-state

Dead simple React global state management based on use-sync-external-store.

mit licence npm version bundlephobia

Installation

$ npm install --save react-atomic-state
# --- or ---
$ yarn add react-atomic-state

❓Motivation

I'm a huge fan of the "state and props" couple, but sometimes I need to share a simple value to my entire application. As I'm not a fan of the Context API and found existing global state management libraries overkill to me most of the times, I decided to publish this small library to cover this specific need 🙌.

Usage

// states/count.ts
import { atom, useAtom, useAtomWithSelector } from "react-atomic-state";

const count = atom(0);

export const decrement = () => count.set((prevCount) => prevCount - 1);
export const increment = () => count.set((prevCount) => prevCount + 1);

const unsubscribe = count.subscribe((value) => {
  console.log(value); // log every update
});

// create a custom hook
export const useCount = () => useAtom(count);

// create a custom hook with selector
// (not to create a complex object store - it's often better to create multiple atoms, but to derive data)
export const useStringCount = () =>
  useAtomWithSelector(count, (count) => count.toString());
import { decrement, increment, useCount } from "./states/count.ts";

const Counter = () => {
  const count = useCount();

  return (
    <div>
      <span>count: {count}</span>

      <button onClick={decrement}>-1</button>
      <button onClick={increment}>+1</button>
    </div>
  );
};

API

atom()

type atom = <Value>(initialValue: Value) => {
  get: () => Value;
  set: (value: Value | ((prevValue: Value) => Value)) => void;
  subscribe: (callback: (value: Value) => void) => () => void;
  reset: () => void;
};

useAtom()

type useAtom = <Value>(
  atom: Atom<Value>,
  isEqual?: (prevValue: Value, nextValue: Value) => boolean,
) => Value;

useAtomWithSelector()

type useAtomWithSelector = <Value, Selection>(
  atom: Atom<Value>,
  selector: (value: Value) => Selection,
  isEqual?: (prevSelection: Selection, nextSelection: Selection) => boolean,
) => Value;
2.0.0

5 months ago

1.2.7

1 year ago

1.2.6

2 years ago

1.2.5

2 years ago

1.2.4

2 years ago

1.2.3

2 years ago

1.2.2

2 years ago

1.2.1

2 years ago

1.2.0

2 years ago

1.1.1

2 years ago

1.1.0

2 years ago

1.0.4

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago