createUseActions
createUseActions is a utility function for generating a custom hook that provides bound action creators. It simplifies dispatching Redux actions by encapsulating the useDispatch logic and is intended as an alternative to the withProps HOC for applications using React hooks.
Importing
To use createUseActions, import it from @blue-functor/remodel:
import { createUseActions } from '@blue-functor/remodel';Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
actions | Record<string, ActionCreator> | Yes | An object containing action creators to be wrapped for use in the generated hook. |
Returns
A custom React hook that returns a set of bound action creators. Each action creator can be called directly with its payload, and the corresponding action is automatically dispatched.
Example Usage
Creating a Hook for Actions
import { createUseActions } from '@blue-functor/remodel';
import * as actions from './actions';
export const useUiActions = createUseActions(actions);Using the Hook in a Component
import React from 'react';
import { useUiActions } from '@/models/ui';
const UiComponent: React.FC = () => {
const { setMode } = useUiActions();
return (
<div>
<button onClick={() => setMode(true)}>Enable Mode</button>
<button onClick={() => setMode(false)}>Disable Mode</button>
</div>
);
};
export default UiComponent;In this example:
useUiActionsis a custom hook created usingcreateUseActions.- The
setModeaction is bound to the Reduxdispatchfunction, allowing it to be called directly with a payload.
Notes
-
Intended Use:
createUseActionsis designed as an alternative to thewithPropsHOC for applications that prefer React hooks over higher-order components. -
Type Safety: The returned hook ensures type safety, inferring the correct payload type for each action creator.
-
Usage in Modular Applications: Include the generated hooks, like
useUiActions, in the model-specifichooks.tsfiles for better organization and reusability.
How It Works
-
Action Binding:
- Iterates over the provided
actionsobject and binds each action creator to the Reduxdispatchfunction. - Returns an object where each key matches the original
actionsobject but wraps the corresponding action creator withdispatch.
- Iterates over the provided
-
Encapsulation:
- Encapsulates the
useDispatchlogic, reducing boilerplate and keeping components focused on their primary purpose.
- Encapsulates the
By using createUseActions, you simplify action handling in your components while maintaining a clean and modern React hooks-based architecture.