Selector

A Redux like system to optimize rendering of components.

Usage

Creates a new selector using createSelector. A selector is composed with a Provider and a useSelector hook.

You give a state prop to the Provider and subscribe to a small part of this state using useSelector. It is the same idea as Redux, a big state object and small subscriptions to only render components that needs it.

A selector follows the same philosophy of context, you should not expose your selector directly but only hooks.

The first argument of useSelector is a selector function (state: TState) => TSelected, the second one, optional is a comparison function. The signature is exactly the same as React Redux useSelector.

// ArticleSelector.js
import { createSelector } from "swash/utils/selector";

// Selector is private and not exposed directly
const Selector = createSelector();

export const ArticleSelectorProvider = ({ article, children }) => {
  return <Selector.Provider state={article}>{children}</Selector.Provider>;
};

export const useArticleSelector = Selector.useSelector;
// ArticleRoot.js
import { ArticleSelectorProvider } from "./ArticleSelector";

function Article({ article }) {
  // We provide the complete article object
  return (
    <ArticleSelectorProvider article={article}>
      {/* ... */}
    </ArticleSelectorProvider>
  );
}
// ArticleTitle.js
import { useArticleSelector } from "./ArticleSelector";

function ArticleTitle() {
  // This component will only re-render when title changes
  const title = useArticleSelector((article) => article.title);
  return <h1>{title}</h1>;
}