createUseSelectors
createUseSelectors is a utility function for generating a custom hook that provides access to Redux state through selectors. It simplifies state access by encapsulating useSelector logic and returning an object containing the results of multiple selectors. Like createUseActions, this utility is intended as an alternative to the withProps HOC for applications using React hooks.
Importing
To use createUseSelectors, import it from @blue-functor/remodel:
import { createUseSelectors } from '@blue-functor/remodel';Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
selectors | Record<string, (state: any) => any> | Yes | An object containing selector functions to retrieve state slices. |
Returns
A custom React hook that returns an object where each key matches the provided selectors and contains the corresponding selected state.
Example Usage
Creating a Hook for Selectors
import { createUseSelectors } from '@blue-functor/remodel';
import * as selectors from './selectors';
export const useUiSelectors = createUseSelectors(selectors);Using the Hook in a Component
import React from 'react';
import { useUiSelectors } from '../models/ui/hooks';
const UiComponent: React.FC = () => {
const { mode } = useUiSelectors();
return (
<div>
<p>Current Mode: {mode ? 'Enabled' : 'Disabled'}</p>
</div>
);
};
export default UiComponent;In this example:
useUiSelectorsis a custom hook created usingcreateUseSelectors.- The
modeselector retrieves the current mode from the Redux state and is directly accessible in the component.
Notes
-
Intended Use:
createUseSelectorsis designed as an alternative to thewithPropsHOC, enabling applications to leverage React hooks for accessing Redux state. -
Performance Considerations:
The
useSelectorhook ensures each selector is independently subscribed to the Redux store. This means that changes in unrelated state slices will not trigger unnecessary re-renders, enhancing performance.
-
Grouping selectors into a single custom hook improves maintainability without sacrificing performance, as each selector is still individually optimized.
-
Usage in Modular Applications: Include the generated hooks, like
useUiSelectors, in the model-specifichooks.tsfiles for better organization and reusability.
How It Works
-
Selector Binding:
- Iterates over the provided
selectorsobject and appliesuseSelectorto each selector function. - Returns an object where each key corresponds to a selector, with its value set to the result of the
useSelectorcall.
- Iterates over the provided
-
Encapsulation:
- Encapsulates
useSelectorlogic for multiple selectors into a single hook, reducing boilerplate and simplifying state access in components.
- Encapsulates
By using createUseSelectors, you can efficiently access Redux state in a hooks-based architecture, improving both readability and performance while maintaining clean and modular code.