use-sharable-state
v2.0.1
Published
This packages makes sharing states simpler
Downloads
9
Maintainers
Readme
Sharable State Hook
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;