Skip to content

Instantly share code, notes, and snippets.

@MarekZeman91
Created July 3, 2024 16:39
Show Gist options
  • Save MarekZeman91/e48e15f37ac0b6dddd3db861c5a96096 to your computer and use it in GitHub Desktop.
Save MarekZeman91/e48e15f37ac0b6dddd3db861c5a96096 to your computer and use it in GitHub Desktop.
import { useMemo } from "react";
import { useArrayHash } from "./useArrayHash";
export function useMemoizedArray<T1, T2 = T1>(
array: T1[],
hashKey: keyof T1,
): [T2[], string];
export function useMemoizedArray<T1, T2 = T1>(
array: T1[],
hashKey: keyof T1,
mapper: (item: T1, i: number, array: T1[]) => T2,
): [T2[], string];
export function useMemoizedArray<T1, T2>(
array: T1[],
hashKey: keyof T1,
mapItem?: (item: T1, i: number, array: T1[]) => T2,
): [T1[] | T2[], string] {
const hash = useArrayHash(array, hashKey);
const memo = useMemo(() => {
return mapItem ? array.map(mapItem) : array;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [hash]);
return [memo, hash];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment