Skip to content

Commit 8cf9d0d

Browse files
committed
refactor: export useDispatch, only return restate in useRestate
- useDispatch now returns store.dispatch - useRestate will now only return the state and not dispatch
1 parent d36b938 commit 8cf9d0d

2 files changed

Lines changed: 17 additions & 11 deletions

File tree

example/Comp.tsx

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

44
export default function Component() {
5-
const [restate, dispatch] = useRestate((state: { count: number }) => {
5+
const dispatch = useDispatch();
6+
const { count } = useRestate((state: { count: number }) => {
67
return { count: state.count };
78
});
89

910
const incrementAction = { type: 'INCREMENT' };
11+
const derementAction = { type: 'DECREMENT' };
1012
const increment = useAction(incrementAction);
1113

1214
return (
1315
<div>
14-
<p>{restate.count}</p>
16+
<p>{count}</p>
1517
<a onClick={increment}>Increment count</a>
16-
<a onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement count</a>
18+
<a onClick={() => dispatch(derementAction)}>Decrement count</a>
1719
</div>
1820
);
1921
}

src/index.ts

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,7 @@ const useStore = () => {
1717
return store;
1818
};
1919

20-
export function useRestate<TState, USelector>(
21-
selectFrom: (state: TState) => USelector,
22-
): [USelector, Dispatch] {
20+
export function useRestate<TState, TSelector>(selectFrom: (state: TState) => TSelector): TSelector {
2321
const store = useStore();
2422

2523
const [restate, setRestate] = useState(() => selectFrom(store.getState()));
@@ -49,12 +47,18 @@ export function useRestate<TState, USelector>(
4947
[store, selectFrom],
5048
);
5149

52-
return [restate, store.dispatch];
50+
return restate;
5351
}
5452

55-
export function useAction<TAction extends Action>(action: TAction): () => TAction {
53+
export function useDispatch<TAction extends Action>(): Dispatch<TAction> {
5654
const store = useStore();
57-
const dispatch = useCallback(() => store.dispatch(action), [action]);
5855

59-
return dispatch;
56+
return store.dispatch;
57+
}
58+
59+
export function useAction<TAction extends Action>(action: TAction): () => TAction {
60+
const dispatch = useDispatch();
61+
const memoizedDispatch = useCallback(() => dispatch(action), [action]);
62+
63+
return memoizedDispatch;
6064
}

0 commit comments

Comments
 (0)