-
Notifications
You must be signed in to change notification settings - Fork 186
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: introduced useActions hook for max cleanliness
- Loading branch information
1 parent
0b118ff
commit 1bffd50
Showing
2 changed files
with
54 additions
and
84 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
import type { ActionCreatorsMapObject } from '@reduxjs/toolkit' | ||
import { bindActionCreators } from '@reduxjs/toolkit' | ||
import { useMemo } from 'react' | ||
import { useDispatch } from 'react-redux' | ||
|
||
// A hook that binds Redux action creators to dispatch, allowing them to be called directly without | ||
// manually calling `dispatch` and memoizing with `useCallback`. Returns an object with the same | ||
// shape as the input actions, but with each action creator wrapped to automatically dispatch its | ||
// action. | ||
export function useActions<T extends ActionCreatorsMapObject>( | ||
actions: T, | ||
): { | ||
[P in keyof T]: T[P] extends (...args: any[]) => any | ||
? (...args: Parameters<T[P]>) => ReturnType<T[P]> | ||
: T[P] | ||
} { | ||
const dispatch = useDispatch() | ||
|
||
return useMemo(() => bindActionCreators(actions, dispatch), [actions, dispatch]) | ||
} |