Allow passing a default equality function to `createSelectorHook`
See original GitHub issueNew Features
Allow passing a default equality function to createSelectorHook
What is the new or updated feature that you are suggesting?
I’d like to suggest adding a second argument to createSelectorHook
to overwrite the default equality function.
Why should this feature be included?
My redux store consists for the most part out of custom classes from a functional programming library. This library, prelude-ts, relies on hash codes and an internal .equals()
function on its objects to check equality between objects that do not share a reference:
const a = Vector.of(1, 2, 3);
const b = Vector.of(1, 2, 3);
console.log(a === b) // False
console.log(a.equals(b)) // True
I assume other functional programming languages do something similar, and even outside of an FP context, this seems like a moderately frequent use-case to me in a language that does not support operator overloading.
To ensure I don’t rerender my components unnecessarily, I pass my own equality function for now:
// helpers.ts
const preludeEq = (a: HasEquals, b: any): boolean => a.equals(b);
// In some component:
import { useSelector } from 'react-redux';
import { preludeEq } from '../helpers';
const ProjectList = () => {
const projects: Vector<string> = useSelector(store => store.project, preludeEq);
return (
<ul>
{projects.map((name) => <li>{name}</li>)}
</ul>
);
}
I would like to instead be able to create my own useSelector hook and pass preludeEq as a default equality function. Something like:
// helpers.ts
const preludeEq = (a: HasEquals, b: any): boolean => a.equals(b);
// store.ts
import { preludeEq } from '../helpers';
export const useSelector = createSelectorHook(null, preludeEq);
// In some component:
import { useSelector } from "../store";
const ProjectList = () => {
const projects: Vector<string> = useSelector(store => store.project);
return (
<ul>
{projects.map((name) => <li>{name}</li>)}
</ul>
);
}
What docs changes are needed to explain this?
createSelectorHook
actually doesn’t seem to be referenced in the docs, but this might touch upon:
I’m more than willing to submit a pull request for this 😃 Since the first argument to createReactHook
is optional, this change could be fully backward compatible.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:3
- Comments:8 (4 by maintainers)
Top GitHub Comments
Actually, yeah, that would be much easier than changing our API. You need to create a hook anyways, and it doesn’t have to come from the factory function.
Sorry for my ignorance but…
const MySelector = (selector) => { return useSelector(selector, yourOwnEqualityFn) }
That hook doesnt solve the problem?