Skip to content

Instantly share code, notes, and snippets.

@codemile
Created January 2, 2025 17:04
Show Gist options
  • Save codemile/c8069dbe46bff33f0a94ca9790796744 to your computer and use it in GitHub Desktop.
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
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;
}
@codemile
Copy link
Author

codemile commented Jan 2, 2025

This hook, useWhiteBlackList, allows you to filter a list of items based on optional whitelist and blacklist arrays. You provide a custom includes function to determine if an item belongs to a given list. Here's how it works:

  1. Inputs: You can pass a whitelist, blacklist, and the main list of items to filter.
  2. Whitelist Logic: If a whitelist is provided, the hook filters items that match the whitelist using the custom includes function.
  3. Blacklist Logic: If no whitelist is provided but a blacklist is, the hook filters out items matching the blacklist.
  4. Fallback: If neither a whitelist nor a blacklist is provided, the original list is returned unchanged.
  5. Custom Includes Function: The includes function is referenced with useRef 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment