use-sharable-state
TypeScript icon, indicating that this package has built-in type declarations

2.0.1 • Public • Published

Sharable State Hook

npm (scoped) codecov npm peer dependency version (scoped) npm GitHub GitHub issues

The most performant and simple state sharing react hook that is only 1 KB!!

It can be used for both React and React Native applications.


Installation

with NPM:

npm install --save use-sharable-state

with Yarn:

yarn add use-sharable-state

with PNPM:

pnpm add use-sharable-state

Usage

You can use it like useState hook but with one extra key parameter for each different state:

import { useCallback } from "react";
import { useSharableState } from "use-sharable-state";

const COUNTER_STATE_KEY = "counter";

const CounterComponent = () => {
  const [count, setCount] = useSharableState(COUNTER_STATE_KEY, 0);

  const increaseCounter = useCallback(() => {
    setCount((oldCount) => oldCount + 1) // or setCount(count + 1~~~~)
  }, [setCount])

  return (
    <div>
      <h1>Counter</h1>

      <p>{count}</p>

      <button
        type="button"
        onClick={increaseCounter}
      >
        Add
      </button>
    </div>
  );
};

for better usability and defining actions, you need to create a custom hook and isolate the actions that change the state:

import { useSharableState } from "use-sharable-state";

const MESSAGE_COUNTER = "messageCounter";

const useMessageCounter = () => {
  const [count, setCount] = useSharableState(MESSAGE_COUNTER, 0);

  const increase = () => setCount((value) => value + 1);

  const decrease = () => setCount((value) => (value === 0 ? value : value - 1));

  return {
    count,

    increase,
    decrease,
  };
};

export default useMessageCounter;

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 2.0.1
    0
    • latest

Version History

Package Sidebar

Install

npm i use-sharable-state

Weekly Downloads

9

Version

2.0.1

License

MIT

Unpacked Size

42.3 kB

Total Files

21

Last publish

Collaborators

  • sam-afshari