reselect

  • Version 5.1.0
  • Published
  • 623 kB
  • No dependencies
  • MIT license

Install

npm i reselect
yarn add reselect
pnpm add reselect

Overview

Selectors for Redux.

Index

Variables

variable createSelector

const createSelector: CreateSelectorFunction<
<Func extends AnyFunction>(
func: Func,
options?: WeakMapMemoizeOptions<ReturnType<Func>>
) => Func & {
clearCache: () => void;
resultsCount: () => number;
resetResultsCount: () => void;
},
<Func extends AnyFunction>(
func: Func,
options?: WeakMapMemoizeOptions<ReturnType<Func>>
) => Func & {
clearCache: () => void;
resultsCount: () => number;
resetResultsCount: () => void;
},
any
>;
  • Accepts one or more "input selectors" (either as separate arguments or a single array), a single "result function" / "combiner", and an optional options object, and generates a memoized selector function.

    See Also

    Modifiers

    • @public

variable createStructuredSelector

const createStructuredSelector: StructuredSelectorCreator<any>;
  • A convenience function that simplifies returning an object made up of selector results.

    Parameter inputSelectorsObject

    A key value pair consisting of input selectors.

    Parameter selectorCreator

    A custom selector creator function. It defaults to createSelector.

    Returns

    A memoized structured selector.

    Example 1

    Modern Use Case

    import { createSelector, createStructuredSelector } from 'reselect'
    interface RootState {
    todos: {
    id: number
    completed: boolean
    title: string
    description: string
    }[]
    alerts: { id: number; read: boolean }[]
    }
    // This:
    const structuredSelector = createStructuredSelector(
    {
    todos: (state: RootState) => state.todos,
    alerts: (state: RootState) => state.alerts,
    todoById: (state: RootState, id: number) => state.todos[id]
    },
    createSelector
    )
    // Is essentially the same as this:
    const selector = createSelector(
    [
    (state: RootState) => state.todos,
    (state: RootState) => state.alerts,
    (state: RootState, id: number) => state.todos[id]
    ],
    (todos, alerts, todoById) => {
    return {
    todos,
    alerts,
    todoById
    }
    }
    )

    See Also

    Modifiers

    • @public

variable referenceEqualityCheck

const referenceEqualityCheck: EqualityFn<any>;
  • Runs a simple reference equality check. What uses by default.

    **Note**: This function was previously known as defaultEqualityCheck.

    Modifiers

    • @public

Functions

function createSelectorCreator

createSelectorCreator: {
<
MemoizeFunction extends UnknownMemoizer<UnknownFunction>,
ArgsMemoizeFunction extends UnknownMemoizer<UnknownFunction> = <
Func extends AnyFunction
>(
func: Func,
options?: WeakMapMemoizeOptions<ReturnType<Func>>
) => Func & {
clearCache: () => void;
resultsCount: () => number;
resetResultsCount: () => void;
}
>(
options: Simplify<
SetRequired<
CreateSelectorOptions<
typeof weakMapMemoize,
typeof weakMapMemoize,
MemoizeFunction,
ArgsMemoizeFunction
>,
'memoize'
>
>
): CreateSelectorFunction<MemoizeFunction, ArgsMemoizeFunction>;
<MemoizeFunction extends UnknownMemoizer<UnknownFunction>>(
memoize: MemoizeFunction,
...memoizeOptionsFromArgs: DropFirstParameter<MemoizeFunction>
): CreateSelectorFunction<
MemoizeFunction,
<Func extends AnyFunction>(
func: Func,
options?: WeakMapMemoizeOptions<ReturnType<Func>>
) => Func & {
clearCache: () => void;
resultsCount: () => number;
resetResultsCount: () => void;
},
any
>;
};
  • Creates a selector creator function with the specified memoization function and options for customizing memoization behavior.

    Parameter options

    An options object containing the memoize function responsible for memoizing the resultFunc inside createSelector (e.g., lruMemoize or weakMapMemoize). It also provides additional options for customizing memoization. While the memoize property is mandatory, the rest are optional.

    Returns

    A customized createSelector function.

    Example 1

    const customCreateSelector = createSelectorCreator({
    memoize: customMemoize, // Function to be used to memoize `resultFunc`
    memoizeOptions: [memoizeOption1, memoizeOption2], // Options passed to `customMemoize` as the second argument onwards
    argsMemoize: customArgsMemoize, // Function to be used to memoize the selector's arguments
    argsMemoizeOptions: [argsMemoizeOption1, argsMemoizeOption2] // Options passed to `customArgsMemoize` as the second argument onwards
    })
    const customSelector = customCreateSelector(
    [inputSelector1, inputSelector2],
    resultFunc // `resultFunc` will be passed as the first argument to `customMemoize`
    )
    customSelector(
    ...selectorArgs // Will be memoized by `customArgsMemoize`
    )

    MemoizeFunction - The type of the memoize function that is used to memoize the resultFunc inside createSelector (e.g., lruMemoize or weakMapMemoize). ArgsMemoizeFunction - The type of the optional memoize function that is used to memoize the arguments passed into the output selector generated by createSelector (e.g., lruMemoize or weakMapMemoize). If none is explicitly provided, weakMapMemoize will be used.

    See Also

    • 5.0.0

    Modifiers

    • @public
  • Creates a selector creator function with the specified memoization function and options for customizing memoization behavior.

    Parameter memoize

    The memoize function responsible for memoizing the resultFunc inside createSelector (e.g., lruMemoize or weakMapMemoize).

    Parameter memoizeOptionsFromArgs

    Optional configuration options for the memoization function. These options are then passed to the memoize function as the second argument onwards.

    Returns

    A customized createSelector function.

    Example 1

    const customCreateSelector = createSelectorCreator(customMemoize, // Function to be used to memoize `resultFunc`
    option1, // Will be passed as second argument to `customMemoize`
    option2, // Will be passed as third argument to `customMemoize`
    option3 // Will be passed as fourth argument to `customMemoize`
    )
    const customSelector = customCreateSelector(
    [inputSelector1, inputSelector2],
    resultFunc // `resultFunc` will be passed as the first argument to `customMemoize`
    )

    MemoizeFunction - The type of the memoize function that is used to memoize the resultFunc inside createSelector (e.g., lruMemoize or weakMapMemoize).

    See Also

    Modifiers

    • @public

function lruMemoize

lruMemoize: <Func extends AnyFunction>(
func: Func,
equalityCheckOrOptions?: EqualityFn | LruMemoizeOptions<ReturnType<Func>>
) => Func & {
clearCache: () => void;
resultsCount: () => number;
resetResultsCount: () => void;
};
  • Creates a memoized version of a function with an optional LRU (Least Recently Used) cache. The memoized function uses a cache to store computed values. Depending on the maxSize option, it will use either a singleton cache (for a single entry) or an LRU cache (for multiple entries).

    **Note**: This function was previously known as defaultMemoize.

    Parameter func

    The function to be memoized.

    Parameter equalityCheckOrOptions

    Either an equality check function or an options object.

    Returns

    A memoized function with a .clearCache() method attached.

    Func - The type of the function that is memoized.

    See Also

    Modifiers

    • @public

function setGlobalDevModeChecks

setGlobalDevModeChecks: (devModeChecks: Partial<DevModeChecks>) => void;
  • Overrides the development mode checks settings for all selectors.

    Reselect performs additional checks in development mode to help identify and warn about potential issues in selector behavior. This function allows you to customize the behavior of these checks across all selectors in your application.

    **Note**: This setting can still be overridden per selector inside createSelector's options object. See and for more details.

    _The development mode checks do not run in production builds._

    Parameter devModeChecks

    An object specifying the desired settings for development mode checks. You can provide partial overrides. Unspecified settings will retain their current values.

    Example 1

    import { setGlobalDevModeChecks } from 'reselect'
    import { DevModeChecks } from '../types'
    // Run only the first time the selector is called. (default)
    setGlobalDevModeChecks({ inputStabilityCheck: 'once' })
    // Run every time the selector is called.
    setGlobalDevModeChecks({ inputStabilityCheck: 'always' })
    // Never run the input stability check.
    setGlobalDevModeChecks({ inputStabilityCheck: 'never' })
    // Run only the first time the selector is called. (default)
    setGlobalDevModeChecks({ identityFunctionCheck: 'once' })
    // Run every time the selector is called.
    setGlobalDevModeChecks({ identityFunctionCheck: 'always' })
    // Never run the identity function check.
    setGlobalDevModeChecks({ identityFunctionCheck: 'never' })

    See Also

    • 5.0.0

    Modifiers

    • @public

function unstable_autotrackMemoize

unstable_autotrackMemoize: <Func extends AnyFunction>(
func: Func
) => Func & {
clearCache: () => void;
resultsCount: () => number;
resetResultsCount: () => void;
};
  • Uses an "auto-tracking" approach inspired by the work of the Ember Glimmer team. It uses a Proxy to wrap arguments and track accesses to nested fields in your selector on first read. Later, when the selector is called with new arguments, it identifies which accessed fields have changed and only recalculates the result if one or more of those accessed fields have changed. This allows it to be more precise than the shallow equality checks in lruMemoize.

    __Design Tradeoffs for autotrackMemoize:__ - Pros: - It is likely to avoid excess calculations and recalculate fewer times than lruMemoize will, which may also result in fewer component re-renders. - Cons: - It only has a cache size of 1. - It is slower than lruMemoize, because it has to do more work. (How much slower is dependent on the number of accessed fields in a selector, number of calls, frequency of input changes, etc) - It can have some unexpected behavior. Because it tracks nested field accesses, cases where you don't access a field will not recalculate properly. For example, a badly-written selector like: ```ts createSelector([state => state.todos], todos => todos) ``` that just immediately returns the extracted value will never update, because it doesn't see any field accesses to check.

    __Use Cases for autotrackMemoize:__ - It is likely best used for cases where you need to access specific nested fields in data, and avoid recalculating if other fields in the same data objects are immutably updated.

    Parameter func

    The function to be memoized.

    Returns

    A memoized function with a .clearCache() method attached.

    Example 1

    Using createSelector

    import { unstable_autotrackMemoize as autotrackMemoize, createSelector } from 'reselect'
    const selectTodoIds = createSelector(
    [(state: RootState) => state.todos],
    (todos) => todos.map(todo => todo.id),
    { memoize: autotrackMemoize }
    )

    Example 2

    Using createSelectorCreator

    import { unstable_autotrackMemoize as autotrackMemoize, createSelectorCreator } from 'reselect'
    const createSelectorAutotrack = createSelectorCreator({ memoize: autotrackMemoize })
    const selectTodoIds = createSelectorAutotrack(
    [(state: RootState) => state.todos],
    (todos) => todos.map(todo => todo.id)
    )

    Func - The type of the function that is memoized.

    See Also

    • 5.0.0

    Modifiers

    • @public
    • @experimental

function weakMapMemoize

weakMapMemoize: <Func extends AnyFunction>(
func: Func,
options?: WeakMapMemoizeOptions<ReturnType<Func>>
) => Func & {
clearCache: () => void;
resultsCount: () => number;
resetResultsCount: () => void;
};
  • Creates a tree of WeakMap-based cache nodes based on the identity of the arguments it's been called with (in this case, the extracted values from your input selectors). This allows weakMapMemoize to have an effectively infinite cache size. Cache results will be kept in memory as long as references to the arguments still exist, and then cleared out as the arguments are garbage-collected.

    __Design Tradeoffs for weakMapMemoize:__ - Pros: - It has an effectively infinite cache size, but you have no control over how long values are kept in cache as it's based on garbage collection and WeakMaps. - Cons: - There's currently no way to alter the argument comparisons. They're based on strict reference equality. - It's roughly the same speed as lruMemoize, although likely a fraction slower.

    __Use Cases for weakMapMemoize:__ - This memoizer is likely best used for cases where you need to call the same selector instance with many different arguments, such as a single selector instance that is used in a list item component and called with item IDs like: ```ts useSelector(state => selectSomeData(state, props.category)) ```

    Parameter func

    The function to be memoized.

    Returns

    A memoized function with a .clearCache() method attached.

    Example 1

    Using createSelector

    import { createSelector, weakMapMemoize } from 'reselect'
    interface RootState {
    items: { id: number; category: string; name: string }[]
    }
    const selectItemsByCategory = createSelector(
    [
    (state: RootState) => state.items,
    (state: RootState, category: string) => category
    ],
    (items, category) => items.filter(item => item.category === category),
    {
    memoize: weakMapMemoize,
    argsMemoize: weakMapMemoize
    }
    )

    Example 2

    Using createSelectorCreator

    import { createSelectorCreator, weakMapMemoize } from 'reselect'
    const createSelectorWeakMap = createSelectorCreator({ memoize: weakMapMemoize, argsMemoize: weakMapMemoize })
    const selectItemsByCategory = createSelectorWeakMap(
    [
    (state: RootState) => state.items,
    (state: RootState, category: string) => category
    ],
    (items, category) => items.filter(item => item.category === category)
    )

    Func - The type of the function that is memoized.

    See Also

    • 5.0.0

    Modifiers

    • @public
    • @experimental

Interfaces

interface CreateSelectorFunction

interface CreateSelectorFunction<
MemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize,
ArgsMemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize,
StateType = any
> {}
  • An instance of createSelector, customized with a given memoize implementation.

    MemoizeFunction - The type of the memoize function that is used to memoize the resultFunc inside createSelector (e.g., lruMemoize or weakMapMemoize). ArgsMemoizeFunction - The type of the optional memoize function that is used to memoize the arguments passed into the output selector generated by createSelector (e.g., lruMemoize or weakMapMemoize). If none is explicitly provided, weakMapMemoize will be used. StateType - The type of state that the selectors created with this selector creator will operate on.

    Modifiers

    • @public

property withTypes

withTypes: <OverrideStateType extends StateType>() => CreateSelectorFunction<
MemoizeFunction,
ArgsMemoizeFunction,
OverrideStateType
>;
  • Creates a "pre-typed" version of where the state type is predefined.

    This allows you to set the state type once, eliminating the need to specify it with every call.

    Returns

    A pre-typed createSelector with the state type already defined.

    Example 1

    import { createSelector } from 'reselect'
    export interface RootState {
    todos: { id: number; completed: boolean }[]
    alerts: { id: number; read: boolean }[]
    }
    export const createAppSelector = createSelector.withTypes<RootState>()
    const selectTodoIds = createAppSelector(
    [
    // Type of `state` is set to `RootState`, no need to manually set the type
    state => state.todos
    ],
    todos => todos.map(({ id }) => id)
    )

    OverrideStateType - The specific type of state used by all selectors created with this selector creator.

    See Also

    • 5.1.0

call signature

<InputSelectors extends SelectorArray<StateType>, Result>(
...createSelectorArgs: [
...inputSelectors: InputSelectors,
combiner: Combiner<InputSelectors, Result>
]
): OutputSelector<InputSelectors, Result, MemoizeFunction, ArgsMemoizeFunction> &
InterruptRecursion;
  • Creates a memoized selector function.

    Parameter createSelectorArgs

    An arbitrary number of input selectors as separate inline arguments and a combiner function.

    Returns

    A memoized output selector.

    InputSelectors - The type of the input selectors as an array. Result - The return type of the combiner as well as the output selector. OverrideMemoizeFunction - The type of the optional memoize function that could be passed into the options object to override the original memoize function that was initially passed into createSelectorCreator. OverrideArgsMemoizeFunction - The type of the optional argsMemoize function that could be passed into the options object to override the original argsMemoize function that was initially passed into createSelectorCreator.

    See Also

call signature

<
InputSelectors extends SelectorArray<StateType>,
Result,
OverrideMemoizeFunction extends UnknownMemoizer = MemoizeFunction,
OverrideArgsMemoizeFunction extends UnknownMemoizer = ArgsMemoizeFunction
>(
...createSelectorArgs: [
...inputSelectors: InputSelectors,
combiner: Combiner<InputSelectors, Result>,
createSelectorOptions: Simplify<
CreateSelectorOptions<
MemoizeFunction,
ArgsMemoizeFunction,
OverrideMemoizeFunction,
OverrideArgsMemoizeFunction
>
>
]
): OutputSelector<
InputSelectors,
Result,
OverrideMemoizeFunction,
OverrideArgsMemoizeFunction
> &
InterruptRecursion;
  • Creates a memoized selector function.

    Parameter createSelectorArgs

    An arbitrary number of input selectors as separate inline arguments, a combiner function and an options object.

    Returns

    A memoized output selector.

    InputSelectors - The type of the input selectors as an array. Result - The return type of the combiner as well as the output selector. OverrideMemoizeFunction - The type of the optional memoize function that could be passed into the options object to override the original memoize function that was initially passed into createSelectorCreator. OverrideArgsMemoizeFunction - The type of the optional argsMemoize function that could be passed into the options object to override the original argsMemoize function that was initially passed into createSelectorCreator.

    See Also

call signature

<
InputSelectors extends SelectorArray<StateType>,
Result,
OverrideMemoizeFunction extends UnknownMemoizer = MemoizeFunction,
OverrideArgsMemoizeFunction extends UnknownMemoizer = ArgsMemoizeFunction
>(
inputSelectors: [...InputSelectors],
combiner: Combiner<InputSelectors, Result>,
createSelectorOptions?: Simplify<
CreateSelectorOptions<
MemoizeFunction,
ArgsMemoizeFunction,
OverrideMemoizeFunction,
OverrideArgsMemoizeFunction
>
>
): OutputSelector<
InputSelectors,
Result,
OverrideMemoizeFunction,
OverrideArgsMemoizeFunction
> &
InterruptRecursion;
  • Creates a memoized selector function.

    Parameter inputSelectors

    An array of input selectors.

    Parameter combiner

    A function that Combines the input selectors and returns an output selector. Otherwise known as the result function.

    Parameter createSelectorOptions

    An optional options object that allows for further customization per selector.

    Returns

    A memoized output selector.

    InputSelectors - The type of the input selectors array. Result - The return type of the combiner as well as the output selector. OverrideMemoizeFunction - The type of the optional memoize function that could be passed into the options object to override the original memoize function that was initially passed into createSelectorCreator. OverrideArgsMemoizeFunction - The type of the optional argsMemoize function that could be passed into the options object to override the original argsMemoize function that was initially passed into createSelectorCreator.

    See Also

interface CreateSelectorOptions

interface CreateSelectorOptions<
MemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize,
ArgsMemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize,
OverrideMemoizeFunction extends UnknownMemoizer = never,
OverrideArgsMemoizeFunction extends UnknownMemoizer = never
> {}
  • The options object used inside createSelector and createSelectorCreator.

    MemoizeFunction - The type of the memoize function that is used to memoize the resultFunc inside createSelector (e.g., lruMemoize or weakMapMemoize). ArgsMemoizeFunction - The type of the optional memoize function that is used to memoize the arguments passed into the output selector generated by createSelector (e.g., lruMemoize or weakMapMemoize). If none is explicitly provided, weakMapMemoize will be used. OverrideMemoizeFunction - The type of the optional memoize function that could be passed into the options object inside createSelector to override the original memoize function that was initially passed into createSelectorCreator. OverrideArgsMemoizeFunction - The type of the optional argsMemoize function that could be passed into the options object inside createSelector to override the original argsMemoize function that was initially passed into createSelectorCreator. If none was initially provided, weakMapMemoize will be used.

    Modifiers

    • @public

property argsMemoize

argsMemoize?: FallbackIfNever<OverrideArgsMemoizeFunction, ArgsMemoizeFunction>;
  • The optional memoize function that is used to memoize the arguments passed into the output selector generated by createSelector (e.g., lruMemoize or weakMapMemoize).

    When passed directly into createSelector, it overrides the argsMemoize function initially passed into createSelectorCreator. If none was initially provided, weakMapMemoize will be used.

    Example 1

    import { createSelector, weakMapMemoize } from 'reselect'
    const selectItemsByCategory = createSelector(
    [
    (state: RootState) => state.items,
    (state: RootState, category: string) => category
    ],
    (items, category) => items.filter(item => item.category === category),
    { argsMemoize: weakMapMemoize }
    )

    weakMapMemoize

    5.0.0

property argsMemoizeOptions

argsMemoizeOptions?: OverrideMemoizeOptions<
ArgsMemoizeFunction,
OverrideArgsMemoizeFunction
>;
  • Optional configuration options for the function. These options are passed to the function as the second argument.

    5.0.0

property devModeChecks

devModeChecks?: Partial<DevModeChecks>;
  • Reselect performs additional checks in development mode to help identify and warn about potential issues in selector behavior. This option allows you to customize the behavior of these checks per selector.

    See Also

    • 5.0.0

property memoize

memoize?: FallbackIfNever<OverrideMemoizeFunction, MemoizeFunction>;
  • The memoize function that is used to memoize the inside createSelector (e.g., lruMemoize or weakMapMemoize).

    When passed directly into createSelector, it overrides the memoize function initially passed into createSelectorCreator.

    Example 1

    import { createSelector, weakMapMemoize } from 'reselect'
    const selectItemsByCategory = createSelector(
    [
    (state: RootState) => state.items,
    (state: RootState, category: string) => category
    ],
    (items, category) => items.filter(item => item.category === category),
    { memoize: weakMapMemoize }
    )

    5.0.0

property memoizeOptions

memoizeOptions?: OverrideMemoizeOptions<
MemoizeFunction,
OverrideMemoizeFunction
>;
  • Optional configuration options for the function. These options are passed to the function as the second argument.

    5.0.0

interface DevModeChecks

interface DevModeChecks {}
  • Represents the configuration for development mode checks.

    5.0.0

    Modifiers

    • @public

property identityFunctionCheck

identityFunctionCheck: DevModeCheckFrequency;
  • Overrides the global identity function check for the selector. - once - Run only the first time the selector is called. - always - Run every time the selector is called. - never - Never run the identity function check.

    'once'

    See Also

    • 5.0.0

property inputStabilityCheck

inputStabilityCheck: DevModeCheckFrequency;
  • Overrides the global input stability check for the selector. - once - Run only the first time the selector is called. - always - Run every time the selector is called. - never - Never run the input stability check.

    'once'

    See Also

    • 5.0.0

interface LruMemoizeOptions

interface LruMemoizeOptions<Result = any> {}
  • Options for configuring the behavior of a function memoized with LRU (Least Recently Used) caching.

    Result - The type of the return value of the memoized function.

    Modifiers

    • @public

property equalityCheck

equalityCheck?: EqualityFn;
  • Function used to compare the individual arguments of the provided calculation function.

    referenceEqualityCheck

property maxSize

maxSize?: number;
  • The maximum size of the cache used by the selector. A size greater than 1 means the selector will use an LRU (Least Recently Used) cache, allowing for the caching of multiple results based on different sets of arguments.

    1

property resultEqualityCheck

resultEqualityCheck?: EqualityFn<Result>;
  • If provided, used to compare a newly generated output value against previous values in the cache. If a match is found, the old value is returned. This addresses the common

    todos.map(todo => todo.id)

    use case, where an update to another field in the original data causes a recalculation due to changed references, but the output is still effectively the same.

    4.1.0

interface StructuredSelectorCreator

interface StructuredSelectorCreator<StateType = any> {}
  • It provides a way to create structured selectors. The structured selector can take multiple input selectors and map their output to an object with specific keys.

    StateType - The type of state that the structured selectors created with this structured selector creator will operate on.

    See Also

    Modifiers

    • @public

property withTypes

withTypes: <
OverrideStateType extends StateType
>() => StructuredSelectorCreator<OverrideStateType>;
  • Creates a "pre-typed" version of where the state type is predefined.

    This allows you to set the state type once, eliminating the need to specify it with every call.

    Returns

    A pre-typed createStructuredSelector with the state type already defined.

    Example 1

    import { createStructuredSelector } from 'reselect'
    export interface RootState {
    todos: { id: number; completed: boolean }[]
    alerts: { id: number; read: boolean }[]
    }
    export const createStructuredAppSelector =
    createStructuredSelector.withTypes<RootState>()
    const structuredAppSelector = createStructuredAppSelector({
    // Type of `state` is set to `RootState`, no need to manually set the type
    todos: state => state.todos,
    alerts: state => state.alerts,
    todoById: (state, id: number) => state.todos[id]
    })

    OverrideStateType - The specific type of state used by all structured selectors created with this structured selector creator.

    See Also

    • 5.1.0

call signature

<
InputSelectorsObject extends SelectorsObject<StateType>,
MemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize,
ArgsMemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize
>(
inputSelectorsObject: InputSelectorsObject,
selectorCreator?: CreateSelectorFunction<
MemoizeFunction,
ArgsMemoizeFunction
>
): OutputSelector<
ObjectValuesToTuple<InputSelectorsObject>,
Simplify<SelectorResultsMap<InputSelectorsObject>>,
MemoizeFunction,
ArgsMemoizeFunction
> &
InterruptRecursion;
  • A convenience function that simplifies returning an object made up of selector results.

    Parameter inputSelectorsObject

    A key value pair consisting of input selectors.

    Parameter selectorCreator

    A custom selector creator function. It defaults to createSelector.

    Returns

    A memoized structured selector.

    Example 1

    Modern Use Case

    import { createSelector, createStructuredSelector } from 'reselect'
    interface RootState {
    todos: {
    id: number
    completed: boolean
    title: string
    description: string
    }[]
    alerts: { id: number; read: boolean }[]
    }
    // This:
    const structuredSelector = createStructuredSelector(
    {
    todos: (state: RootState) => state.todos,
    alerts: (state: RootState) => state.alerts,
    todoById: (state: RootState, id: number) => state.todos[id]
    },
    createSelector
    )
    // Is essentially the same as this:
    const selector = createSelector(
    [
    (state: RootState) => state.todos,
    (state: RootState) => state.alerts,
    (state: RootState, id: number) => state.todos[id]
    ],
    (todos, alerts, todoById) => {
    return {
    todos,
    alerts,
    todoById
    }
    }
    )

    Example 2

    In your component:

    import type { RootState } from 'createStructuredSelector/modernUseCase'
    import { structuredSelector } from 'createStructuredSelector/modernUseCase'
    import type { FC } from 'react'
    import { useSelector } from 'react-redux'
    interface Props {
    id: number
    }
    const MyComponent: FC<Props> = ({ id }) => {
    const { todos, alerts, todoById } = useSelector((state: RootState) =>
    structuredSelector(state, id)
    )
    return (
    <div>
    Next to do is:
    <h2>{todoById.title}</h2>
    <p>Description: {todoById.description}</p>
    <ul>
    <h3>All other to dos:</h3>
    {todos.map(todo => (
    <li key={todo.id}>{todo.title}</li>
    ))}
    </ul>
    </div>
    )
    }

    Example 3

    Simple Use Case

    const selectA = state => state.a
    const selectB = state => state.b
    // The result function in the following selector
    // is simply building an object from the input selectors
    const structuredSelector = createSelector(selectA, selectB, (a, b) => ({
    a,
    b
    }))
    const result = structuredSelector({ a: 1, b: 2 }) // will produce { x: 1, y: 2 }

    InputSelectorsObject - The shape of the input selectors object. MemoizeFunction - The type of the memoize function that is used to create the structured selector. It defaults to weakMapMemoize. ArgsMemoizeFunction - The type of the of the memoize function that is used to memoize the arguments passed into the generated structured selector. It defaults to weakMapMemoize.

    See Also

interface WeakMapMemoizeOptions

interface WeakMapMemoizeOptions<Result = any> {}
  • Configuration options for a memoization function utilizing WeakMap for its caching mechanism.

    Result - The type of the return value of the memoized function.

    5.0.0

    Modifiers

    • @public

property resultEqualityCheck

resultEqualityCheck?: EqualityFn<Result>;
  • If provided, used to compare a newly generated output value against previous values in the cache. If a match is found, the old value is returned. This addresses the common

    todos.map(todo => todo.id)

    use case, where an update to another field in the original data causes a recalculation due to changed references, but the output is still effectively the same.

    5.0.0

Type Aliases

type Combiner

type Combiner<InputSelectors extends SelectorArray, Result> = Distribute<
/**
* A function that takes input selectors' return values as arguments and returns a result. Otherwise known as `resultFunc`.
*
* @param resultFuncArgs - Return values of input selectors.
* @returns The return value of {@linkcode OutputSelectorFields.resultFunc resultFunc}.
*/
(...resultFuncArgs: SelectorResultArray<InputSelectors>) => Result
>;
  • A function that takes input selectors' return values as arguments and returns a result. Otherwise known as resultFunc.

    InputSelectors - An array of input selectors. Result - Result returned by resultFunc.

    Modifiers

    • @public

type DefaultMemoizeFields

type DefaultMemoizeFields = {
/**
* Clears the memoization cache associated with a memoized function.
* This method is typically used to reset the state of the cache, allowing
* for the garbage collection of previously memoized results and ensuring
* that future calls to the function recompute the results.
*/
clearCache: () => void;
resultsCount: () => number;
resetResultsCount: () => void;
};
  • Represents the additional properties attached to a function memoized by reselect.

    lruMemoize, weakMapMemoize and autotrackMemoize all return these properties.

    See Also

    Modifiers

    • @public

type DevModeCheckFrequency

type DevModeCheckFrequency = 'always' | 'once' | 'never';
  • The frequency of development mode checks.

    5.0.0

    Modifiers

    • @public

type DevModeChecksExecutionInfo

type DevModeChecksExecutionInfo = {
[K in keyof DevModeChecks]: {
/**
* A boolean indicating whether the check should be executed.
*/
shouldRun: boolean;
/**
* The function to execute for the check.
*/
run: AnyFunction;
};
};
  • Represents execution information for development mode checks.

    5.0.0

    Modifiers

    • @public

type EqualityFn

type EqualityFn<T = any> = (a: T, b: T) => boolean;
  • A standard function returning true if two values are considered equal.

    Modifiers

    • @public

type ExtractMemoizerFields

type ExtractMemoizerFields<MemoizeFunction extends UnknownMemoizer> = Simplify<
OmitIndexSignature<ReturnType<MemoizeFunction>>
>;
  • Extracts the additional properties or methods that a memoize function attaches to the function it memoizes (e.g., clearCache).

    MemoizeFunction - The type of the memoize function to be checked.

    Modifiers

    • @public

type GetParamsFromSelectors

type GetParamsFromSelectors<Selectors extends SelectorArray> = ArrayTail<
MergeParameters<Selectors>
>;
  • Determines the combined "Params" type (all remaining args) from all input selectors.

    Modifiers

    • @public

type GetStateFromSelectors

type GetStateFromSelectors<Selectors extends SelectorArray> =
MergeParameters<Selectors>[0];
  • Determines the combined single "State" type (first arg) from all input selectors.

    Modifiers

    • @public

type MemoizeOptionsFromParameters

type MemoizeOptionsFromParameters<MemoizeFunction extends UnknownMemoizer> =
| (
| NonFunctionType<DropFirstParameter<MemoizeFunction>[0]>
| FunctionType<DropFirstParameter<MemoizeFunction>[0]>
)
| (
| NonFunctionType<DropFirstParameter<MemoizeFunction>[number]>
| FunctionType<DropFirstParameter<MemoizeFunction>[number]>
)[];
  • Extracts the options type for a memoization function based on its parameters. The first parameter of the function is expected to be the function to be memoized, followed by options for the memoization process.

    MemoizeFunction - The type of the memoize function to be checked.

    Modifiers

    • @public

type OutputSelector

type OutputSelector<
InputSelectors extends SelectorArray = SelectorArray,
Result = unknown,
MemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize,
ArgsMemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize
> = Selector<
GetStateFromSelectors<InputSelectors>,
Result,
GetParamsFromSelectors<InputSelectors>
> &
ExtractMemoizerFields<ArgsMemoizeFunction> &
OutputSelectorFields<
InputSelectors,
Result,
MemoizeFunction,
ArgsMemoizeFunction
>;
  • Represents the actual selectors generated by createSelector.

    InputSelectors - The type of the input selectors. Result - The type of the result returned by the resultFunc. MemoizeFunction - The type of the memoize function that is used to memoize the resultFunc inside createSelector (e.g., lruMemoize or weakMapMemoize). ArgsMemoizeFunction - The type of the optional memoize function that is used to memoize the arguments passed into the output selector generated by createSelector (e.g., lruMemoize or weakMapMemoize). If none is explicitly provided, weakMapMemoize will be used.

    Modifiers

    • @public

type OutputSelectorFields

type OutputSelectorFields<
InputSelectors extends SelectorArray = SelectorArray,
Result = unknown,
MemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize,
ArgsMemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize
> = {
/**
* The final function passed to `createSelector`. Otherwise known as the `combiner`.
*/
resultFunc: Combiner<InputSelectors, Result>;
/**
* The memoized version of {@linkcode OutputSelectorFields.resultFunc resultFunc}.
*/
memoizedResultFunc: Combiner<InputSelectors, Result> &
ExtractMemoizerFields<MemoizeFunction>;
/**
* @Returns The last result calculated by {@linkcode OutputSelectorFields.memoizedResultFunc memoizedResultFunc}.
*/
lastResult: () => Result;
/**
* The array of the input selectors used by `createSelector` to compose the
* combiner ({@linkcode OutputSelectorFields.memoizedResultFunc memoizedResultFunc}).
*/
dependencies: InputSelectors;
/**
* Counts the number of times {@linkcode OutputSelectorFields.memoizedResultFunc memoizedResultFunc} has been recalculated.
*/
recomputations: () => number;
/**
* Resets the count of {@linkcode OutputSelectorFields.recomputations recomputations} count to 0.
*/
resetRecomputations: () => void;
/**
* Counts the number of times the input selectors ({@linkcode OutputSelectorFields.dependencies dependencies})
* have been recalculated. This is distinct from {@linkcode OutputSelectorFields.recomputations recomputations},
* which tracks the recalculations of the result function.
*
* @since 5.0.0
*/
dependencyRecomputations: () => number;
/**
* Resets the count {@linkcode OutputSelectorFields.dependencyRecomputations dependencyRecomputations}
* for the input selectors ({@linkcode OutputSelectorFields.dependencies dependencies})
* of a memoized selector.
*
* @since 5.0.0
*/
resetDependencyRecomputations: () => void;
} & Simplify<
Required<
Pick<
CreateSelectorOptions<MemoizeFunction, ArgsMemoizeFunction>,
'argsMemoize' | 'memoize'
>
>
>;
  • The additional fields attached to the output selector generated by createSelector.

    **Note**: Although and are included in the attached fields, the fields themselves are independent of the type of and functions. Meaning this type is not going to generate additional fields based on what functions we use to memoize our selectors.

    _This type is not to be confused with ._

    InputSelectors - The type of the input selectors. Result - The type of the result returned by the resultFunc. MemoizeFunction - The type of the memoize function that is used to memoize the resultFunc inside createSelector (e.g., lruMemoize or weakMapMemoize). ArgsMemoizeFunction - The type of the optional memoize function that is used to memoize the arguments passed into the output selector generated by createSelector (e.g., lruMemoize or weakMapMemoize). If none is explicitly provided, weakMapMemoize will be used.

    Modifiers

    • @public

type OverrideMemoizeOptions

type OverrideMemoizeOptions<
MemoizeFunction extends UnknownMemoizer,
OverrideMemoizeFunction extends UnknownMemoizer = never
> = IfNever<
OverrideMemoizeFunction,
Simplify<MemoizeOptionsFromParameters<MemoizeFunction>>,
Simplify<MemoizeOptionsFromParameters<OverrideMemoizeFunction>>
>;
  • Derive the type of memoize options object based on whether the memoize function itself was overridden.

    _This type can be used for both memoizeOptions and argsMemoizeOptions._

    MemoizeFunction - The type of the memoize or argsMemoize function initially passed into createSelectorCreator. OverrideMemoizeFunction - The type of the optional memoize or argsMemoize function passed directly into createSelector which then overrides the original memoize or argsMemoize function passed into createSelectorCreator.

    Modifiers

    • @public

type RootStateSelectors

type RootStateSelectors<RootState = any> = {
[Key in keyof RootState]: Selector<RootState, RootState[Key], []>;
};
  • Represents a mapping of selectors for each key in a given root state.

    This type is a utility that takes a root state object type and generates a corresponding set of selectors. Each selector is associated with a key in the root state, allowing for the selection of specific parts of the state.

    RootState - The type of the root state object.

    5.0.0

    Modifiers

    • @public

type Selector

type Selector<
State = any,
Result = unknown,
Params extends readonly any[] = any[]
> = Distribute<
/**
* A function that takes a state and returns data that is based on that state.
*
* @param state - The first argument, often a Redux root state object.
* @param params - All additional arguments passed into the selector.
* @returns A derived value from the state.
*/
(state: State, ...params: FallbackIfNever<Params, []>) => Result
>;
  • A standard selector function. State - The first value, often a Redux root state object. Result - The final result returned by the selector. Params - All additional arguments passed into the selector.

    Modifiers

    • @public

type SelectorArray

type SelectorArray<State = any> = readonly Selector<State>[];
  • An array of input selectors.

    Modifiers

    • @public

type SelectorResultArray

type SelectorResultArray<Selectors extends SelectorArray> =
ExtractReturnType<Selectors>;
  • Extracts an array of all return types from all input selectors.

    Modifiers

    • @public

type SelectorResultsMap

type SelectorResultsMap<TObject extends SelectorsObject> = {
[Key in keyof TObject]: ReturnType<TObject[Key]>;
};
  • Represents a mapping of selectors to their return types.

    TObject - An object type where each property is a selector function.

    Modifiers

    • @public

type SelectorsObject

type SelectorsObject<StateType = any> = Record<string, Selector<StateType>>;
  • Represents an object where each property is a selector function.

    StateType - The type of state that all the selectors operate on.

    Modifiers

    • @public

type TypedStructuredSelectorCreator

type TypedStructuredSelectorCreator<RootState = any> =
/**
* A convenience function that simplifies returning an object
* made up of selector results.
*
* @param inputSelectorsObject - A key value pair consisting of input selectors.
* @param selectorCreator - A custom selector creator function. It defaults to `createSelector`.
* @returns A memoized structured selector.
*
* @example
* <caption>Modern Use Case</caption>
* ```ts
* import { createSelector, createStructuredSelector } from 'reselect'
*
* interface RootState {
* todos: {
* id: number
* completed: boolean
* title: string
* description: string
* }[]
* alerts: { id: number; read: boolean }[]
* }
*
* // This:
* const structuredSelector = createStructuredSelector(
* {
* todos: (state: RootState) => state.todos,
* alerts: (state: RootState) => state.alerts,
* todoById: (state: RootState, id: number) => state.todos[id]
* },
* createSelector
* )
*
* // Is essentially the same as this:
* const selector = createSelector(
* [
* (state: RootState) => state.todos,
* (state: RootState) => state.alerts,
* (state: RootState, id: number) => state.todos[id]
* ],
* (todos, alerts, todoById) => {
* return {
* todos,
* alerts,
* todoById
* }
* }
* )
* ```
*
* @example
* <caption>In your component:</caption>
* ```tsx
* import type { RootState } from 'createStructuredSelector/modernUseCase'
* import { structuredSelector } from 'createStructuredSelector/modernUseCase'
* import type { FC } from 'react'
* import { useSelector } from 'react-redux'
*
* interface Props {
* id: number
* }
*
* const MyComponent: FC<Props> = ({ id }) => {
* const { todos, alerts, todoById } = useSelector((state: RootState) =>
* structuredSelector(state, id)
* )
*
* return (
* <div>
* Next to do is:
* <h2>{todoById.title}</h2>
* <p>Description: {todoById.description}</p>
* <ul>
* <h3>All other to dos:</h3>
* {todos.map(todo => (
* <li key={todo.id}>{todo.title}</li>
* ))}
* </ul>
* </div>
* )
* }
* ```
*
* @example
* <caption>Simple Use Case</caption>
* ```ts
* const selectA = state => state.a
* const selectB = state => state.b
*
* // The result function in the following selector
* // is simply building an object from the input selectors
* const structuredSelector = createSelector(selectA, selectB, (a, b) => ({
* a,
* b
* }))
*
* const result = structuredSelector({ a: 1, b: 2 }) // will produce { x: 1, y: 2 }
* ```
*
* @template InputSelectorsObject - The shape of the input selectors object.
* @template MemoizeFunction - The type of the memoize function that is used to create the structured selector. It defaults to `weakMapMemoize`.
* @template ArgsMemoizeFunction - The type of the of the memoize function that is used to memoize the arguments passed into the generated structured selector. It defaults to `weakMapMemoize`.
*
* @see {@link https://reselect.js.org/api/createStructuredSelector `createStructuredSelector`}
*/
<
InputSelectorsObject extends RootStateSelectors<RootState> = RootStateSelectors<RootState>,
MemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize,
ArgsMemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize
>(
inputSelectorsObject: InputSelectorsObject,
selectorCreator?: CreateSelectorFunction<
MemoizeFunction,
ArgsMemoizeFunction
>
) => OutputSelector<
ObjectValuesToTuple<InputSelectorsObject>,
Simplify<SelectorResultsMap<InputSelectorsObject>>,
MemoizeFunction,
ArgsMemoizeFunction
> &
InterruptRecursion;
  • Modifiers

    • @public

    Deprecated

    Please use instead. This type will be removed in the future. RootState - The type of the root state object.

    5.0.0

type UnknownMemoizer

type UnknownMemoizer<FunctionType extends UnknownFunction = UnknownFunction> = (
func: FunctionType,
...options: any[]
) => FunctionType;
  • Any Memoizer function. A memoizer is a function that accepts another function and returns it.

    FunctionType - The type of the function that is memoized.

    Modifiers

    • @public

Package Files (1)

Dependencies (0)

No dependencies.

Dev Dependencies (28)

Peer Dependencies (0)

No peer dependencies.

Badge

To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/reselect.

  • Markdown
    [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/reselect)
  • HTML
    <a href="https://www.jsdocs.io/package/reselect"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>