| 1 | import { useEffect, useRef } from "react"; |
| 2 | |
| 3 | export function useMemoCompare<T>( |
| 4 | next: T | null | undefined, |
| 5 | compare: ( |
| 6 | previous: T | null | undefined, |
| 7 | next: T | null | undefined |
| 8 | ) => boolean |
| 9 | ) { |
| 10 | // Ref for storing previous value |
| 11 | const previousRef = useRef<T | null | undefined>(); |
| 12 | const previous = previousRef.current; |
| 13 | // Pass previous and next value to compare function |
| 14 | // to determine whether to consider them equal. |
| 15 | const isEqual = compare(previous, next); |
| 16 | // If not equal update previousRef to next value. |
| 17 | // We only update if not equal so that this hook continues to return |
| 18 | // the same old value if compare keeps returning true. |
| 19 | useEffect(() => { |
| 20 | if (!isEqual) { |
| 21 | previousRef.current = next; |
| 22 | } |
| 23 | }); |
| 24 | // Finally, if equal then return the previous value |
| 25 | return isEqual ? previous : next; |
| 26 | } |