MCPcopy Create free account
hub / github.com/triggerdotdev/jsonhero-web / useMemoCompare

Function useMemoCompare

app/hooks/useMemoCompare.ts:3–26  ·  view source on GitHub ↗
(
  next: T | null | undefined,
  compare: (
    previous: T | null | undefined,
    next: T | null | undefined
  ) => boolean
)

Source from the content-addressed store, hash-verified

1import { useEffect, useRef } from "react";
2
3export 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}

Callers 1

useColumnViewFunction · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected