Features
- Easy share state anywhere
- No more complex concepts, only useHook
- Write in TypeScript
- Boilerplate Code Generator support use-one-templates
- 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 { 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
createOne
- e.g:createOne<Type>(initialState, Options?: {useEffect?: boolean, name?: string})
if the options useEffect is false, will use useLayoutEffect- returns
[useHook, store]
store
methods:.getState()
get the state.replaceState(newState)
set the state.subscribe(cb: (state) => {})
subscribe.replaceState
update, return unsubscribe function.syncState(newState)
sync state without update, useful for list components update.destroy
clear event
- returns
Boilerplate Code Generator
Please see use-one-templates, it’s very useful to create many share states in large application.
Online Example
Count
TextInput