Skip to content

Commit 553cbb4

Browse files
committed
fix: bound dynamicNameCache to prevent memory leak
Components with free-form string interpolations (e.g. `color: ${p => p.$value}` from unbounded user input) previously accumulated cached class names indefinitely for the lifetime of the component definition. Cap aligned to the existing warnTooManyClasses threshold so the dev warning fires before eviction begins.
1 parent 248edc3 commit 553cbb4

3 files changed

Lines changed: 50 additions & 0 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'styled-components': patch
3+
---
4+
5+
Fix memory leak in long-running apps using components with free-form string interpolations (e.g. `color: ${p => p.$dynamicValue}` where the value comes from unbounded user input).

‎packages/styled-components/src/models/ComponentStyle.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { ExecutionContext, RuleSet, Stringifier } from '../types';
55
import flatten from '../utils/flatten';
66
import generateName from '../utils/generateAlphabeticName';
77
import getComponentName from '../utils/getComponentName';
8+
import { LIMIT as TOO_MANY_CLASSES_LIMIT } from '../utils/createWarnTooManyClasses';
89
import { hash, phash } from '../utils/hash';
910
import isKeyframes from '../utils/isKeyframes';
1011
import isPlainObject from '../utils/isPlainObject';
@@ -13,6 +14,17 @@ import { joinRules, joinStringArray, joinStrings } from '../utils/joinStrings';
1314

1415
const SEED = hash(SC_VERSION);
1516

17+
/**
18+
* Upper bound on dynamicNameCache entries per ComponentStyle instance.
19+
* Without this cap, components with free-form string interpolations
20+
* (e.g. `color: ${p => p.$color}` where $color is unbounded user input)
21+
* leak memory for the lifetime of the component definition. Aligned to
22+
* the warnTooManyClasses dev threshold so the warning and the eviction
23+
* share a single source of truth: by the time you start dropping cache
24+
* entries, the dev warning has already told you why.
25+
*/
26+
const MAX_DYNAMIC_NAME_CACHE = TOO_MANY_CLASSES_LIMIT;
27+
1628
/**
1729
* RSC optimization: caches compiled CSS per class name so the RSC emission
1830
* path can read directly without round-tripping through the sheet tag.
@@ -139,6 +151,10 @@ export default class ComponentStyle {
139151
let name = this.dynamicNameCache.get(cacheKey);
140152
if (!name) {
141153
name = generateName(phash(phash(this.baseHash, stylis.hash), css) >>> 0);
154+
if (this.dynamicNameCache.size >= MAX_DYNAMIC_NAME_CACHE) {
155+
const oldest = this.dynamicNameCache.keys().next().value;
156+
if (oldest !== undefined) this.dynamicNameCache.delete(oldest);
157+
}
142158
this.dynamicNameCache.set(cacheKey, name);
143159
}
144160

‎packages/styled-components/src/test/memoization.test.tsx‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -317,4 +317,33 @@ describe('memoization correctness', () => {
317317

318318
renderer.unmount();
319319
});
320+
321+
it('bounds dynamicNameCache size for free-form interpolations', () => {
322+
// Regression: dynamicNameCache previously grew unbounded for components
323+
// with free-form string interpolations, leaking for the lifetime of
324+
// the component definition.
325+
const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
326+
const Comp = styled.div<{ $value: string }>`
327+
color: ${p => p.$value};
328+
`;
329+
330+
const renderer = TestRenderer.create(<Comp $value="rgb(0,0,0)" />);
331+
for (let i = 0; i < 500; i++) {
332+
renderer.update(<Comp $value={`rgb(${i},${i},${i})`} />);
333+
}
334+
335+
const { dynamicNameCache } = Comp.componentStyle;
336+
expect(dynamicNameCache?.size).toBeGreaterThan(0);
337+
expect(dynamicNameCache?.size).toBeLessThanOrEqual(200);
338+
339+
const recentValue = 'rgb(499,499,499)';
340+
renderer.update(<Comp $value={recentValue} />);
341+
const recentClass = renderer.root.findByType('div').props.className;
342+
renderer.update(<Comp $value="rgb(0,0,0)" />);
343+
renderer.update(<Comp $value={recentValue} />);
344+
expect(renderer.root.findByType('div').props.className).toBe(recentClass);
345+
346+
renderer.unmount();
347+
warnSpy.mockRestore();
348+
});
320349
});

0 commit comments

Comments
 (0)