Wondering what’s next for npm?Check out our public roadmap! »

    react-atomic-state
    TypeScript icon, indicating that this package has built-in type declarations

    1.0.3 • Public • Published

    ⚛️ react-atomic-state

    bundlephobia npm version styled with prettier

    Dead simple React global state management based on use-subscription.

    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.
    I don't like the Context API and existing global state management libraries (overkill to me most of the times: state must be an object, you have to deal with selectors, etc.), so I decided to publish this small library to cover this specific need 🙌.

    Usage

    // states/count.ts
    import { atom, useAtom } 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);
    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>) => Value;

    Install

    npm i react-atomic-state

    DownloadsWeekly Downloads

    14

    Version

    1.0.3

    License

    MIT

    Unpacked Size

    10.6 kB

    Total Files

    8

    Last publish

    Collaborators

    • avatar