javascript / expert
Snippet
Referential Stability via Deep Comparative Tracking
React's built-in hooks use referential equality (===). For objects created inline, this causes effects to re-run every render. This pattern uses a ref to store a 'canonical' version of the object that only updates when its contents change deeply.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
function useDeepMemo(value) {const ref = useRef();if (!isEqual(value, ref.current)) {ref.current = value;}return ref.current;}// Usageconst memoizedValue = useDeepMemo(complexObject);useEffect(() => { /* logic */ }, [memoizedValue]);
react
Breakdown
1
if (!isEqual(value, ref.current))
Performs a deep equality check (e.g., via lodash) instead of a simple reference check.
2
ref.current = value;
Only updates the stored reference if the underlying data has actually changed.
3
return ref.current;
Returns a stable reference that can be safely used in dependency arrays.