useCustomCompareEffect
A hook like useEffect but with a custom compare function
Only when the user's ID changes will the effect be triggered
Loading...
Installation
npx shadcn@latest add @shadcnhooks/use-custom-compare-effectAPI
/**
* A hook like useEffect but with a custom compare function
* @param effect - The effect to use
* @param deps - The dependencies to use
* @param customCompare - The custom compare function to use
*/
function useCustomCompareEffect<T extends DependencyList>(
effect: EffectCallback,
deps: T,
customCompare: (a: T, b: T) => boolean,
): voidNotes
Important: Do not call
setStatemethods inside thecustomComparefunction. The compare function should be a pure function that only performs comparison logic.
// ❌ Don't do this
const compareById = (a: User[], b: User[]) => {
const result = a[0]?.id === b[0]?.id
setCount((prev) => prev + 1) // ❌ This will cause infinite re-renders
return result
}
// ✅ Do this instead
const compareById = (a: User[], b: User[]) => {
const result = a[0]?.id === b[0]?.id
return result
}Credits
Last updated on