Skip to content

Instantly share code, notes, and snippets.

@ksimons
Created October 12, 2022 12:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ksimons/3c05c9c466bac1e3d1a9b9af742bee3b to your computer and use it in GitHub Desktop.
Save ksimons/3c05c9c466bac1e3d1a9b9af742bee3b to your computer and use it in GitHub Desktop.
Recoil.js selector family that allows for equality checking
function equalSelectorFamily<T, P extends SerializableParam>(
options: EqualSelectorFamilyOptions<T, P>
) {
const inner = selectorFamily<T, P>({
key: `${options.key}_inner`,
get: options.get,
});
const priorValues: Map<P, T | undefined> = new Map();
return selectorFamily<T, P>({
...options,
key: options.key,
get:
(param: P) =>
({ get }) => {
const latest = get(inner(param));
const prior = priorValues.get(param);
if (prior != null && options.equals(latest, prior)) {
return prior;
}
priorValues.set(param, latest);
return latest;
},
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment