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
yarn
yarn add use-one eventemitter3
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 });
},
};
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>
);
}
Top comments (2)
Cool. Have you tested with Concurrent Mode to see if it tears?
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.