MCPcopy Index your code
hub / github.com/streamich/react-use / useMethods

Function useMethods

src/useMethods.ts:16–39  ·  view source on GitHub ↗
(
  createMethods: CreateMethods<M, T>,
  initialState: T
)

Source from the content-addressed store, hash-verified

14};
15
16const useMethods = <M, T>(
17 createMethods: CreateMethods<M, T>,
18 initialState: T
19): [T, WrappedMethods<M>] => {
20 const reducer = useMemo<Reducer<T, Action>>(
21 () => (reducerState: T, action: Action) => {
22 return createMethods(reducerState)[action.type](...action.payload);
23 },
24 [createMethods]
25 );
26
27 const [state, dispatch] = useReducer<Reducer<T, Action>>(reducer, initialState);
28
29 const wrappedMethods: WrappedMethods<M> = useMemo(() => {
30 const actionTypes = Object.keys(createMethods(initialState));
31
32 return actionTypes.reduce((acc, type) => {
33 acc[type] = (...payload) => dispatch({ type, payload });
34 return acc;
35 }, {} as WrappedMethods<M>);
36 }, [createMethods, initialState]);
37
38 return [state, wrappedMethods];
39};
40
41export default useMethods;

Callers 2

useMethods.test.tsFile · 0.90
DemoFunction · 0.90

Calls 1

createMethodsFunction · 0.50

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…