Skip to content

Instantly share code, notes, and snippets.

@danielrose7
Created April 17, 2026 21:32
Show Gist options
  • Select an option

  • Save danielrose7/04e80e45ca96c3f7f6bdf654c99efe3f to your computer and use it in GitHub Desktop.

Select an option

Save danielrose7/04e80e45ca96c3f7f6bdf654c99efe3f to your computer and use it in GitHub Desktop.
useArrayMemo / useDeepMemo / useStableMemo hook helper for react where data doesn't change but reference will
import { useState } from 'react';
import isEqual from 'lodash.isequal';
/**
* Memoizes by deep equality — returns the previous reference when
* content is unchanged, even if the input is a new object. Avoids
* unnecessary downstream invalidation that `useMemo` can't prevent
* when its deps are new references with identical data.
*
* Do not pass values containing functions — `isEqual` returns false
* for different instances, causing an infinite re-render loop.
*/
export const useDeepMemo = <T>(nextValue: T): T => {
const [stableValue, setStableValue] = useState<T>(() => nextValue);
if (!isEqual(stableValue, nextValue)) {
setStableValue(() => nextValue);
return nextValue;
}
return stableValue;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment