https://github.com/dioklecijan/react-use-model
How to use custom hooks in React to expose state, actions and state getters.
https://github.com/dioklecijan/react-use-model
hooks-api-react react reducer
Last synced: about 1 year ago
JSON representation
How to use custom hooks in React to expose state, actions and state getters.
- Host: GitHub
- URL: https://github.com/dioklecijan/react-use-model
- Owner: dioklecijan
- License: mit
- Created: 2019-02-28T19:08:28.000Z (about 7 years ago)
- Default Branch: master
- Last Pushed: 2019-02-28T19:12:58.000Z (about 7 years ago)
- Last Synced: 2025-01-20T19:34:13.382Z (over 1 year ago)
- Topics: hooks-api-react, react, reducer
- Language: JavaScript
- Size: 42 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
How to use custom hook to expose state, actions and state getters.
```js
const useModel = () => {
const [state, dispatch] = useReducer(reducer, initState, initFunc);
return {
state,
actions: useMemo(() => mapDispatchToActions(dispatch), [dispatch]),
getters: useMemo(() => mapStateToGetters(state), [state]),
};
};
const App = () => {
const model1 = useModel(); // instance one with state, actions and getters.)
const model2 = useModel(); // instance two
const renderModel = (model, modelName) => {
const { state, actions, getters } = modelName;
return (
actions.inc()}>
Click to inc counter in model {num}
{JSON.stringify(state)}
isCounterEven: {getters.isCounterEven()}
actions.incLazy()}>
inc lazy {JSON.stringify(state)}
isLazyEven: {getters.isLazyEven()}
isCounterSmall: {getters.isCounterSmall}
);
};
...
}
```