Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed #197 优化useGlobalCache中频繁调用useEffectCleanupRegister导致内存过多占用的问题 #198

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion src/hooks/useGlobalCache.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,18 @@ export default function useGlobalCache<CacheType>(
): CacheType {
const { cache: globalCache } = React.useContext(StyleContext);
const fullPath = [prefix, ...keyPath];
const fullPathStr = pathKey(fullPath);

// 缓存fullPathStr,减少render导致的内存占用问题
const stableFullPathStr = React.useRef(pathKey(fullPath));
const fullPathStr = React.useMemo(() => {
const _fullPathStr = pathKey(fullPath);
// 比较fullPathStr变更
if (_fullPathStr !== stableFullPathStr.current) {
stableFullPathStr.current = _fullPathStr;
return _fullPathStr;
}
return stableFullPathStr.current;
}, [fullPath]);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fullPath 每次 render 都是在上面的 fullPath = [prefix, ...keyPath] 重新组合,这个 useMemo 的 deps 永远都不会命中。

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1,如果想要用 useMemo 来优化代码,deps 应该放 fullPath 本身而不是 [fullPath]
另外不太理解为什么缓存 join 会影响内存占用,理论上 useMemo 反而会导致内存占用增加。


const register = useEffectCleanupRegister([fullPathStr]);

Expand Down
Loading