Skip to content

Commit

Permalink
type: update useUniqueMemo params type (ant-design#49389)
Browse files Browse the repository at this point in the history
  • Loading branch information
li-jia-nan authored Jun 13, 2024
1 parent 759f2ff commit d118e31
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 13 deletions.
2 changes: 1 addition & 1 deletion components/_util/__tests__/useUniqueMemo.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ describe('Table', () => {

let calledTimes = 0;

const Test = ({ depName }: { depName: string }) => {
const Test: React.FC<{ depName?: string }> = ({ depName }) => {
useUniqueMemo(() => {
calledTimes += 1;
return depName;
Expand Down
25 changes: 13 additions & 12 deletions components/_util/hooks/useUniqueMemo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,20 @@ const BEAT_LIMIT = 1000 * 60 * 10;
* A helper class to map keys to values.
* It supports both primitive keys and object keys.
*/
class ArrayKeyMap {
map = new Map();
class ArrayKeyMap<T> {
map = new Map<string, T>();

// Use WeakMap to avoid memory leak
objectIDMap = new WeakMap();
objectIDMap = new WeakMap<object, number>();

nextID = 0;

lastAccessBeat = new Map();
lastAccessBeat = new Map<string, number>();

// We will clean up the cache when reach the limit
accessBeat = 0;

set(keys: any[], value: any) {
set(keys: React.DependencyList, value: any) {
// New set will trigger clear
this.clear();

Expand All @@ -29,7 +29,7 @@ class ArrayKeyMap {
this.lastAccessBeat.set(compositeKey, Date.now());
}

get(keys: any[]) {
get(keys: React.DependencyList) {
const compositeKey = this.getCompositeKey(keys);

const cache = this.map.get(compositeKey);
Expand All @@ -39,8 +39,8 @@ class ArrayKeyMap {
return cache;
}

getCompositeKey(keys: any[]) {
const ids = keys.map((key) => {
getCompositeKey(keys: React.DependencyList) {
const ids = keys.map<string>((key) => {
if (key && typeof key === 'object') {
return `obj_${this.getObjectID(key)}`;
}
Expand Down Expand Up @@ -82,15 +82,16 @@ const uniqueMap = new ArrayKeyMap();
/**
* Like `useMemo`, but this hook result will be shared across all instances.
*/
export default function useUniqueMemo<T>(memoFn: () => T, deps: any[]): T {
return React.useMemo(() => {
function useUniqueMemo<T>(memoFn: () => T, deps: React.DependencyList) {
return React.useMemo<T>(() => {
const cachedValue = uniqueMap.get(deps);
if (cachedValue) {
return cachedValue;
return cachedValue as T;
}

const newValue = memoFn();
uniqueMap.set(deps, newValue);
return newValue;
}, deps);
}

export default useUniqueMemo;

0 comments on commit d118e31

Please sign in to comment.