mirror of
https://github.com/streamich/react-use.git
synced 2026-01-18 14:06:52 +00:00
25 lines
659 B
TypeScript
25 lines
659 B
TypeScript
import { useMemo, useReducer } from 'react';
|
|
|
|
const useMethods = (createMethods, initialState) => {
|
|
const reducer = useMemo(
|
|
() => (reducerState, action) => {
|
|
return createMethods(reducerState)[action.type](...action.payload);
|
|
},
|
|
[createMethods]
|
|
);
|
|
|
|
const [state, dispatch] = useReducer(reducer, initialState);
|
|
|
|
const wrappedMethods = useMemo(() => {
|
|
const actionTypes = Object.keys(createMethods(initialState));
|
|
return actionTypes.reduce((acc, type) => {
|
|
acc[type] = (...payload) => dispatch({ type, payload });
|
|
return acc;
|
|
}, {});
|
|
}, []);
|
|
|
|
return [state, wrappedMethods];
|
|
};
|
|
|
|
export default useMethods;
|