DEV Community

suhaotian
suhaotian

Posted on Edited on

use-one: a new state share library for react app...

Hello, everyone! Today, I will share a new state library for react. I already thought this a few years ago until hooks showed up, I can make it real now. The source code is really simple.

Features

  • Easy share state anywhere
  • No more complex concepts, only useHook
  • Write in TypeScript
  • Tiny size (with Dependencies together only gzip 2KB!)

Install

npm

npm install use-one eventemitter3 --save
Enter fullscreen mode Exit fullscreen mode

yarn

yarn add use-one eventemitter3
Enter fullscreen mode Exit fullscreen mode

Usage

Create one hook

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

const initialState = { count: 0 };

type CountStateType = typeof initialState;

const [useCount, countStore] = create<CountStateType>(initialState);

export { useCount, countStore };

export const actions = {
  increment: () => {
    // `countStore.getState().count`, we can write to selectors
    countStore.setState({ count: countStore.getState().count + 1 });
  },
  decrement: () => {
    countStore.setState({ count: countStore.getState().count - 1 });
  },
};
Enter fullscreen mode Exit fullscreen mode

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

Online Example

Count

TextInput

Dependencies

Top comments (2)

Collapse
 
stereoplegic profile image
Mike Bybee •

Cool. Have you tested with Concurrent Mode to see if it tears?

Collapse
 
suhaotian profile image
suhaotian •

The concurrent mode still experimental features. I haven't test it yet.

The source code was very simple, only on/off with useEffect hook, no magic and type safe.