inspired by rematch. use-rematch is a React hook lib, based on useReducer
pnpm i @use-rematch/core
- 📦 No extra dispatch types
- 🔢 Pluginable
- 💗 Model is easy to reuse
you can create reducer
without define DISPATCH_TYPES
import { useRematch } from '@use-rematch/core';
const useHook = () => {
const { state, dispatch } = useRematch({
name: '@use-rematch/basic',
state: {
cnt: 0,
},
reducers: {
add: (state, payload?: number) => {
return {
...state,
cnt: payload ? state.cnt + payload : state.cnt + 1,
};
},
},
effects: {
async asyncAdd(payload: number, state: State) {
this.toggleLoading();
setTimeout(async () => {
this.add(payload);
this.toggleLoading();
}, 1000);
},
},
});
return { state, dispatch }
}
then use dispatchers and state in component. In this way, you can dispatch action like dispatch.add
or dispatch a async action asyncAdd
with intellicode
<div>
<a style={{ marginRight: '16px' }} onClick={() => dispatch.add()}>
add
</a>
<a style={{ marginRight: '16px' }} onClick={() => dispatch.asyncAdd(1)}>
async add after 1s
</a>
<a style={{ marginRight: '16px' }} onClick={() => dispatch.add(-1)}>
reduce
</a>
</div>
for better type intelligence, recommend use
createModel
import { createModel } from '@use-rematch/core'
const model = createModel({
name: '@use-rematch/reuse',
state: {
cnt: 0,
},
reducers: {
add: (state, payload?: number) => {
return {
...state,
cnt: payload ? state.cnt + payload : state.cnt + 1,
};
},
},
effects: {
async asyncAdd(payload: number, state: State) {
this.toggleLoading();
setTimeout(async () => {
this.add(payload);
this.toggleLoading();
}, 1000);
},
},
})
const useHook = () => {
const { state, dispatch } = useRematch(model);
return { state, dispatch }
}
you can use plugin to modify origianl model, for example, @use-rematch/plugin-store will init model state from localstorage, and store model.state to localstorage
import { useRematch } from '@use-rematch/core';
import { createPluginStore } from '@use-rematch/plugin-store'
const PluginStore = createPluginStore()
const useHook = () => {
const { state, dispatch } = useRematch({
name: 'use-rematch-reducer',
state: {
cnt: 0,
loading: false,
},
reducers: {
add: (state, payload?: number) => {
return {
...state,
cnt: payload ? state.cnt + payload : state.cnt + 1,
};
},
},
}, { plugins: [PluginStore] });
return { state, dispatch }
}
currently, pnpm@7
not working on vercel, please still use pnpm@6
👤 JW
- Twitter: @jiangweixian
- Github: @JiangWeixian
Give a ⭐️ if this project helped you!
This README was generated with ❤️ by readme-md-generator