0.1.2 • Published 3 years ago

use-selector-with v0.1.2

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

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);
};