npm install selectre
Tiny time and space efficient state selectors for React, Redux, and more.
- Selectre is built as a more efficient alternative to Reselect
- Selectre is designed to work with Redux's
useSelector()
and React'suseSyncExternalStore()
and ensure the least amount of unnecessary computations for things that don't change. - Selectre uses very efficient implementation of LRU cache to ensure no overhead in accessing cached computation results.
- Selectre uses shallow equality by default to help developers avoid shooting themselves in the foot.
- Selectre caches parametric selectors in the way that allows developers not to use additional measures to memoize stuff in components.
import { createSelector } from "selectre";
import { useSelector } from "react-redux";
let selectNumberCompletedTodos = createSelector(
(state) => state.todos,
(todos) => todos.filter((todo) => todo.completed).length,
);
function CompletedTodosCounter() {
let numberCompletedTodos = useSelector(selectNumberCompletedTodos());
return <span>{numberCompletedTodos}</span>;
}
Selectors uniformity is important because it affects the amount of effort needed to eventually add parameters to a simple selectors.
import { createSelector } from "selectre";
import { useSelector } from "react-redux";
let selectNumberFilteredTodos = createSelector(
(state) => state.todos,
(_, completed) => completed,
(todos, completed) => todos.filter((todo) => todo.completed === completed).length,
);
function TodoCounter({ completed }) {
let numberFilteredTodos = useSelector(selectNumberFilteredTodos(completed));
return <span>{numberFilteredTodos}</span>;
}
let selectNumberCompletedTodos = createSelector(
(state) => state.todos,
(_, completed) => completed,
(todos, completed) => todos.filter((todo) => todo.completed === completed).length,
// isInputEqual for comparing inputs, isOutputEqual for the output
{ isInputEqual: Object.is },
);
import { useSyncExternalStoreWithSelector } from "use-sync-external-store/with-selector";
function useSelector(selector) {
// TODO
}
- The intent and main API is similar and based on Reselect
- LRU cache implementation is based on Guillaume Plique's article about LRU cache and using typed arrays to implement Doubly-Linked Lists (GitHub: @Yomguithereal, Twitter: @Yomguithereal)
- Cache key's hash function implementation is based on
Immutable.js
hashCode()