Skip to content

Commit 80f1368

Browse files
authored
perf: cache effect (#218)
1 parent c13639f commit 80f1368

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

src/hooks/useGlobalCache.tsx

+12-1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ export type ExtractStyle<CacheValue> = (
1212
},
1313
) => [order: number, styleId: string, style: string] | null;
1414

15+
const effectMap = new Map<string, boolean>();
16+
1517
export default function useGlobalCache<CacheType>(
1618
prefix: string,
1719
keyPath: KeyType[],
@@ -73,7 +75,15 @@ export default function useGlobalCache<CacheType>(
7375
// Remove if no need anymore
7476
useInsertionEffect(() => {
7577
buildCache(([times, cache]) => [times + 1, cache]);
76-
onCacheEffect?.(cacheContent);
78+
if (!effectMap.has(fullPathStr)) {
79+
onCacheEffect?.(cacheContent);
80+
effectMap.set(fullPathStr, true);
81+
82+
// 微任务清理混存,可以认为是单次 batch render 中只触发一次 effect
83+
Promise.resolve().then(() => {
84+
effectMap.delete(fullPathStr);
85+
});
86+
}
7787

7888
return () => {
7989
globalCache.opUpdate(fullPathStr, (prevCache) => {
@@ -82,6 +92,7 @@ export default function useGlobalCache<CacheType>(
8292

8393
if (nextCount === 0) {
8494
onCacheRemove?.(cache, false);
95+
effectMap.delete(fullPathStr);
8596
return null;
8697
}
8798

tests/animation.spec.tsx

+3-1
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ describe('animation', () => {
179179
});
180180
});
181181

182-
it('re-mount should not missing animation style', () => {
182+
it('re-mount should not missing animation style', async () => {
183183
function genComp(cls: string) {
184184
return () => {
185185
const [token, hashId] = useCacheToken(theme, [baseToken], {
@@ -211,6 +211,8 @@ describe('animation', () => {
211211
// Clean up
212212
document.head.innerHTML = '';
213213

214+
await Promise.resolve();
215+
214216
// Render again
215217
render(
216218
<StyleProvider cache={createCache()}>

0 commit comments

Comments
 (0)