use-selector-with
TypeScript icon, indicating that this package has built-in type declarations

0.1.2 • Public • Published

use-selector-with

Small utility for react-redux's useSelector that allows passing args.

import { useSelectorWith } from 'use-selector-with';

const selectFruit = (state, name) => state.fruits[name];

const MyComponent = () => {
  const apple = useSelectorWith(selectFruit, 'apple');

  // ...
};

Why?

react-redux's useSelector allows you to extract data from the Redux store state using a selector function, but doesn't allow directly passing arguments to the selector function. See the Using memoizing selectors docs for common workarounds for memoizing selectors.

Instead of creating new lambdas across many lines of code, useSelectorWith assumes shallowEqual and memoizes the selector for you.

Its implementation is teeny:

export const useSelectorWith = (selector: Selector, ...args) => {
  const selectorBound = useCallback(
    (state) => selector(state, ...args),
    [selector, ...args]
  );

  return useSelector(selectorBound, shallowEqual);
};

Package Sidebar

Install

npm i use-selector-with

Weekly Downloads

423

Version

0.1.2

License

MIT

Unpacked Size

8.67 kB

Total Files

14

Last publish

Collaborators

  • codecademy