DocsReact HookscreateUseActions

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

ParameterTypeRequiredDescription
actionsRecord<string, ActionCreator>YesAn 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

src/models/ui/hooks.ts
import { createUseActions } from '@blue-functor/remodel';
import * as actions from './actions';
 
export const useUiActions = createUseActions(actions);

Using the Hook in a Component

src/components/UiComponent.tsx
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:

  • useUiActions is a custom hook created using createUseActions.
  • The setMode action is bound to the Redux dispatch function, allowing it to be called directly with a payload.

Notes

  • Intended Use: createUseActions is designed as an alternative to the withProps HOC 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-specific hooks.ts files for better organization and reusability.


How It Works

  1. Action Binding:

    • Iterates over the provided actions object and binds each action creator to the Redux dispatch function.
    • Returns an object where each key matches the original actions object but wraps the corresponding action creator with dispatch.
  2. Encapsulation:

    • Encapsulates the useDispatch logic, reducing boilerplate and keeping components focused on their primary purpose.

By using createUseActions, you simplify action handling in your components while maintaining a clean and modern React hooks-based architecture.