Created
January 2, 2025 17:04
-
-
Save codemile/c8069dbe46bff33f0a94ca9790796744 to your computer and use it in GitHub Desktop.
Custom React hook for filtering a list using optional whitelist and blacklist arrays with a custom includes function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {useMemo, useRef} from 'react'; | |
export function useWhiteBlackList<TData, TFilter>( | |
{ | |
whitelist: whitelistProp, | |
blacklist: blacklistProp, | |
list | |
}: { | |
whitelist?: Array<TFilter>; | |
blacklist?: Array<TFilter>; | |
list?: Array<TData>; | |
}, | |
includes: (list: Array<TFilter>, item: TData) => boolean | |
): Array<TData> { | |
const ref = useRef(includes); | |
const whitelist = useMemo(() => { | |
if (whitelistProp === undefined) { | |
return undefined; | |
} | |
return list?.filter((item) => ref.current?.(whitelistProp, item)); | |
}, [list, whitelistProp]); | |
const blacklist = useMemo(() => { | |
if (whitelist || blacklistProp === undefined) { | |
return undefined; | |
} | |
return list?.filter((item) => !ref.current?.(blacklistProp, item)); | |
}, [whitelist, list, blacklistProp]); | |
return whitelist ?? blacklist ?? list; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This hook,
useWhiteBlackList
, allows you to filter a list of items based on optional whitelist and blacklist arrays. You provide a customincludes
function to determine if an item belongs to a given list. Here's how it works:whitelist
,blacklist
, and the mainlist
of items to filter.whitelist
is provided, the hook filters items that match the whitelist using the customincludes
function.whitelist
is provided but ablacklist
is, the hook filters out items matching the blacklist.list
is returned unchanged.includes
function is referenced withuseRef
for stability, ensuring it doesn't trigger unnecessary re-renders.This hook is memoized with
useMemo
to optimize performance and recomputes only when the inputs change. It's ideal for managing dynamic list filtering in your React applications.