Skip to content

Commit fe70a45

Browse files
committed
feat: useActions to memoize several actions
1 parent 47b3fde commit fe70a45

2 files changed

Lines changed: 26 additions & 5 deletions

File tree

example/Count.tsx

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,23 @@
11
import React from 'react';
2-
import { useRestate, useAction, useDispatch } from '../src';
2+
import { useRestate, useActions, useDispatch } from '../src';
33

44
export default function Component() {
55
const dispatch = useDispatch();
66
const { count } = useRestate((state: { count: number }) => {
77
return { count: state.count };
88
});
99

10-
const incrementAction = { type: 'INCREMENT' };
11-
const derementAction = { type: 'DECREMENT' };
12-
const increment = useAction(incrementAction);
10+
const { increment, decrement } = useActions({
11+
increment: { type: 'INCREMENT' },
12+
decrement: { type: 'DECREMENT' },
13+
});
1314

1415
return (
1516
<div>
1617
<p>{count}</p>
1718
<a onClick={increment}>Increment count</a>
18-
<a onClick={() => dispatch(derementAction)}>Decrement count</a>
19+
<a onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement count</a>
20+
<a onClick={decrement}>Decrement other</a>
1921
</div>
2022
);
2123
}

src/index.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,3 +62,22 @@ export function useAction<TAction extends Action>(action: TAction): () => TActio
6262

6363
return memoizedDispatch;
6464
}
65+
66+
export function useActions<TAction extends Action>(actions: {
67+
[index: string]: TAction;
68+
}): {
69+
[index: string]: () => TAction;
70+
} {
71+
const dispatch = useDispatch();
72+
const memoizedActions = Object.entries(actions).reduce(
73+
(obj, [key, action]) => {
74+
obj[key] = useCallback(() => dispatch(action), [action]);
75+
return obj;
76+
},
77+
{} as {
78+
[index: string]: () => TAction;
79+
},
80+
);
81+
82+
return memoizedActions;
83+
}

0 commit comments

Comments
 (0)