Features

Install

npm

npm install use-one eventemitter3 --save

yarn

yarn add use-one eventemitter3

Usage

Create one hook

// useCount.ts
import { createOne } from "use-one";

const initialState = { count: 0 };

// export type CountStateType = typeof initialState;
// const [useCount, countStore] = createOne<CountStateType>(initialState);
const [useCount, countStore] = createOne(initialState);

export { useCount, countStore };

export const actions = {
  increment: () => {
    countStore.replaceState({ count: countStore.getState().count + 1 });
  },
  decrement: () => {
    countStore.replaceState({ count: countStore.getState().count - 1 });
  },
};

Use the hook

// CountExample.tsx
import * as React from "react";
import { useCount, countStore, actions } from "./useCount";

const CountExample = () => {
  const [countState, setCountState] = useCount();

  const { count } = countState;

  return (
    <div>
      <button onClick={actions.increment}>+1</button>
      <span>{count}</span>
      <button onClick={actions.decrement}>-1</button>
      <button
        onClick={() => {
          setTimeout(() => {
            setCountState({
              count: countStore.getState().count + 2,
            });
          }, 2000);
        }}>
        async +2
      </button>
    </div>
  );
};

const ShowCountInOtherPlace = () => {
  const [countState] = useCount();
  const { count } = countState;

  return <span>Count: {count}</span>;
};

export default function App() {
  return (
    <Fragment>
      <ShowCountInOtherPlace />
      <CountExample />
    </Fragment>
  );
}

API

Boilerplate Code Generator

Please see use-one-templates, it’s very useful to create many share states in large application.

Online Example

Count

TextInput

More Examples

https://use-one.com/demo.html

More Examples Source Code

Dependencies