Created
April 17, 2026 21:32
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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