Skip to content

Commit 52c5f6e

Browse files
authored
fix: run style interpolations on every render (#5788) (#5809)
* fix: run style interpolations on every render (#5788) The render cache added in 6.4.0 reused a cached result on a props-equal re-render, skipping evaluation of interpolations and attr functions. Those run in the component's own render body, so skipping them dropped any hook they called (crashing with "Rendered fewer hooks than expected", in production too) and served a stale class name or style object when an interpolation read anything outside props and theme. Interpolations and attr functions now run on every render, on both the web and native paths. The pure work downstream of the produced CSS (hashing, compile, injection on web; the CSS-to-style-object transform on native) is still memoized, so repeat renders that yield the same styles stay cheap. A props-equal re-render bailout belongs at the component boundary via React.memo, which only the caller can key correctly. * perf(native): key the inline style cache by CSS string cssToStyleObject keyed its cache by generateComponentId(flatCSS), whose base-52 name conversion and regex ran on every render and dominated the native re-render cost (~80% of per-child work, measured), while the id was only ever used as an internal Map key and never as a class name. Keying by the flat CSS string directly drops generateComponentId from the path. Recovers most of the re-render cost from running interpolations every render (#5788) and makes cache-miss, cycling, and sibling paths faster than before, since the id was on the miss path too. A string key also cannot collide the way the 32-bit hash could, so two distinct CSS strings can no longer return each other's cached style. * refactor(test): share hook-recording helper, clear stale render-cache text Extract the React use*-recording harness (duplicated across the web hook tests and the new native one) into src/test/recordHooks.ts, and update the tests, docs, and agent rules that still described the removed render cache: retitle the HMR class-name test, rewrite the memoization suite's header and hook-sequence test to re-render vocabulary, correct the runtime-performance hot-path wording, and fix an AGENTS rule that read as "hooks must be unconditional" against the deliberate __SERVER__/IS_RSC gating. Trim the changeset to user-observable behavior.
1 parent 3de03c2 commit 52c5f6e

10 files changed

Lines changed: 282 additions & 237 deletions

File tree

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
---
2+
"styled-components": patch
3+
---
4+
5+
Fixed a crash ("Rendered fewer hooks than expected") and a related stale-style bug for components that call a React hook, or read any value outside their props and theme, from inside a style interpolation. This affected `@mui/styled-engine-sc` with MUI X DataGrid, which calls hooks within an interpolation, and was a regression introduced in 6.4.0.
6+
7+
Style interpolations now run on every render, so a hook called inside one runs consistently and a value read inside one always reflects its current state.
8+
9+
If a component re-renders often with unchanged props and its interpolations are expensive, wrap it in `React.memo` to skip those re-renders. That is the right place to bail out, because only the calling code knows the full set of inputs its styles depend on.

‎AGENTS.md‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,15 +24,23 @@ mapped below.
2424
`styleSheet.server` or `IS_RSC`.
2525
- NEVER write `typeof React.useRef === 'function'`; that is a runtime conditional hook. Gate on
2626
`__SERVER__`.
27-
- NEVER place a hook on one side of the render cache's hit/miss branch. The hook sequence must be
28-
identical whether or not props changed. See
27+
- NEVER skip evaluating interpolations or attr functions across renders, and never reintroduce a
28+
props-equal render cache that does. They are the component's own render body and may call hooks or
29+
read state outside props and theme, so skipping them breaks the rules of hooks and serves stale
30+
styles (#5788). A hook may be gated only on a build or runtime constant (`__SERVER__`, `IS_RSC`),
31+
which is stable across a component's renders, never on per-render state. See
2932
[docs/runtime-performance.md](docs/runtime-performance.md).
3033
- NEVER use `new Array(n)`. It creates HOLEY_ELEMENTS arrays that infect V8 type feedback.
3134
- NEVER mutate `rule.props` in place on a stylis AST node; allocate a fresh array.
3235

3336
## Mandates
3437

3538
- React 16.8 compat
39+
- The web and native render paths mirror each other: `src/models/StyledComponent.ts` with
40+
`ComponentStyle.ts` for web, `src/models/StyledNativeComponent.ts` with `InlineStyle.ts` for native.
41+
When changing one, check whether the other needs the same change. A render-path, interpolation, or
42+
attr-evaluation fix on web almost always applies to native, and the reverse. Land both together or
43+
state why one is exempt.
3644
- Always microbenchmark to validate optimizations, and bench the realistic workload rather than a
3745
synthetic best case. Revert changes that pessimize the path actual callers take, even if they win in
3846
isolation.
@@ -77,7 +85,7 @@ it rather than restating it.
7785
detection mechanisms, native entry isolation, module resolution, CSS injection ordering
7886
- [docs/rendering-flow.md](docs/rendering-flow.md) -- the full render sequence diagram
7987
- [docs/runtime-performance.md](docs/runtime-performance.md) -- microbenchmark-validated patterns, the
80-
dynamic re-render hot path and its render cache, V8 gotchas, stylis AST handling
88+
dynamic render hot path, V8 gotchas, stylis AST handling
8189
- [docs/global-styles.md](docs/global-styles.md) -- `createGlobalStyle`'s shared-group architecture,
8290
instance lifecycle, rebuild fast path
8391
- [docs/rsc-style-injection.md](docs/rsc-style-injection.md) -- how styles reach the page from server

‎docs/runtime-performance.md‎

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -14,30 +14,32 @@ microbenchmark against the realistic workload, not a synthetic best case.
1414
| Template literals | Manual `+` concat is 1.3x faster than `` `${a}${b}` `` in tight loops |
1515
| `React.createElement` | Raw element objects measure 60-120x faster, but are NOT used on this branch: `StyledComponent` calls React's own `createElement`. Measurement only, not an inventory entry |
1616

17-
## Dynamic re-render hot path
17+
## Dynamic render hot path
1818

19-
On a cache hit, meaning props and theme are unchanged and this is the most common re-render:
19+
Interpolations and attr functions run on every render. They are the component's own render-body user
20+
code, so a hook called inside an interpolation (React `useContext` from an `@mui/styled-engine-sc`
21+
adapter, for example) is one of the component's hooks and must run every render like any other hook
22+
site. Skipping evaluation on a props-equal re-render would drop that hook and serve a stale class name
23+
whenever an interpolation reads state outside props and theme (#5788).
2024

21-
- `shallowEqualContext` costs roughly 0.2us, comparing props by `for..in` against a stored key count.
22-
- Everything else is skipped: `resolveContext`, flatten, hash and `generateName`.
23-
`buildPropsForElement` still runs.
24-
25-
On a cache miss, meaning props changed:
25+
The pure work downstream of the produced CSS string is memoized, so a repeat render that yields the
26+
same CSS is cheap:
2627

2728
1. `resolveContext`: object spread plus attrs evaluation.
28-
2. `flatten()` fast path: an inline function call for string-returning interpolations, roughly 0.05us
29-
each.
30-
3. `dynamicNameCache` lookup: a `Map.get` on the CSS string, O(1), which skips `phash` and
31-
`generateName` on a hit.
29+
2. Interpolation fast path: an inline function call for string-returning interpolations that bypasses
30+
`flatten`'s type dispatch and array allocation, roughly 0.05us each.
31+
3. `dynamicNameCache` lookup: a `Map.get` on the CSS string (prefixed by the stylis plugin hash when
32+
one is set), O(1), which skips `phash` and `generateName` on a hit.
3233
4. `phash()` and `generateName`: only on a `dynamicNameCache` miss, the first time this CSS is seen.
3334
5. `stylis` compile and serialize: only when `hasNameForId` misses, the first injection of this class.
3435
6. `hasNameForId`: a `Map.has`, negligible.
3536

36-
The render cache splits this path in two, and only the miss side runs the style work. Any hook placed
37-
on one side of that split is called on a miss and skipped on a hit, which makes the component emit a
38-
different hook sequence depending on whether its props happened to change. React rejects that outright
39-
(#5788). `memoization.test.tsx` records the hook sequence across both cache states and asserts they
40-
match, so a hook added inside the branch fails there rather than in a consumer's app.
37+
A props-equal re-render bailout belongs at the component boundary via `React.memo`, which only the
38+
caller can key against the full set of inputs the styles depend on. `memoization.test.tsx` records the
39+
hook sequence across a re-render with unchanged props and asserts it matches the mount, so a change
40+
that reintroduces skipped evaluation fails there rather than in a consumer's app. The native path is
41+
the same: `InlineStyle` caches CSS-to-style-object by content, so `generateStyleObject` returns a
42+
stable reference for equal styles without an outer render cache.
4143

4244
## V8 gotchas
4345

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

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
11
import transformDeclPairs from 'css-to-react-native';
22
import {
3-
Dict,
43
ExecutionContext,
54
IInlineStyle,
65
IInlineStyleConstructor,
76
RuleSet,
87
StyleSheet,
98
} from '../types';
109
import flatten from '../utils/flatten';
11-
import generateComponentId from '../utils/generateComponentId';
1210
import { joinStringArray } from '../utils/joinStrings';
1311

1412
// List of CSS values not supported by React Native
@@ -161,40 +159,42 @@ export function parseCSSDeclarations(rawCss: string): [string, string][] {
161159
return pairs;
162160
}
163161

164-
let generated: Dict<any> = {};
162+
let generated = new Map<string, any>();
165163

166164
/** Clear the cached CSS-to-style-object mappings. Useful in tests or long-running RN apps with highly dynamic styles. */
167165
export const resetStyleCache = (): void => {
168-
generated = {};
166+
generated = new Map();
169167
};
170168

171169
/**
172170
* Parse flat CSS into a style object via css-to-react-native, with caching.
171+
* Keyed by the flat CSS string itself: the transform is a pure function of it,
172+
* and a string key cannot collide the way a 32-bit hash could.
173173
*/
174174
export function cssToStyleObject(flatCSS: string, styleSheet: StyleSheet) {
175-
const hash = generateComponentId(flatCSS);
175+
const cached = generated.get(flatCSS);
176+
if (cached !== undefined) return cached;
176177

177-
if (!generated[hash]) {
178-
const declPairs: [string, string][] = [];
179-
for (const [prop, value] of parseCSSDeclarations(flatCSS)) {
180-
if (RN_UNSUPPORTED_VALUES.includes(value)) {
181-
if (process.env.NODE_ENV !== 'production') {
182-
console.warn(
183-
`[styled-components/native] The value "${value}" for property "${prop}" is not supported in React Native and will be ignored.`
184-
);
185-
}
186-
} else {
187-
declPairs.push([prop, value]);
178+
const declPairs: [string, string][] = [];
179+
for (const [prop, value] of parseCSSDeclarations(flatCSS)) {
180+
if (RN_UNSUPPORTED_VALUES.includes(value)) {
181+
if (process.env.NODE_ENV !== 'production') {
182+
console.warn(
183+
`[styled-components/native] The value "${value}" for property "${prop}" is not supported in React Native and will be ignored.`
184+
);
188185
}
186+
} else {
187+
declPairs.push([prop, value]);
189188
}
189+
}
190190

191-
// RN does not support differing border values for Image components (but does for View).
192-
// https://github.com/styled-components/styled-components/issues/4181
193-
const styleObject = transformDeclPairs(declPairs, ['borderWidth', 'borderColor']);
191+
// RN does not support differing border values for Image components (but does for View).
192+
// https://github.com/styled-components/styled-components/issues/4181
193+
const styleObject = transformDeclPairs(declPairs, ['borderWidth', 'borderColor']);
194194

195-
generated[hash] = styleSheet.create({ generated: styleObject }).generated;
196-
}
197-
return generated[hash];
195+
const result = styleSheet.create({ generated: styleObject }).generated;
196+
generated.set(flatCSS, result);
197+
return result;
198198
}
199199

200200
/**

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

Lines changed: 14 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ import type {
1515
IStyledStatics,
1616
OmitNever,
1717
RuleSet,
18-
Stringifier,
1918
StyledOptions,
2019
WebTarget,
2120
} from '../types';
@@ -40,8 +39,6 @@ import { DefaultTheme, ThemeContext } from './ThemeProvider';
4039

4140
declare const __SERVER__: boolean;
4241

43-
const hasOwn = Object.prototype.hasOwnProperty;
44-
4542
const identifiers: { [key: string]: number } = {};
4643

4744
/** Test-only: clear the per-displayName counter so component IDs stay stable
@@ -71,36 +68,6 @@ function generateId(
7168
return parentComponentId ? parentComponentId + '-' + componentId : componentId;
7269
}
7370

74-
/**
75-
* Shallow-compare two context objects using a stored key count to avoid
76-
* a second iteration pass. Returns true if all own-property values match.
77-
*/
78-
function shallowEqualContext(prev: object, next: object, prevKeyCount: number): boolean {
79-
const a = prev as Record<string, unknown>;
80-
const b = next as Record<string, unknown>;
81-
let nextKeyCount = 0;
82-
for (const key in b) {
83-
if (hasOwn.call(b, key)) {
84-
nextKeyCount++;
85-
if (a[key] !== b[key]) return false;
86-
}
87-
}
88-
return nextKeyCount === prevKeyCount;
89-
}
90-
91-
// Cached render inputs + style result: [prevProps, prevTheme, prevStyleSheet, prevStylis,
92-
// prevPropsKeyCount, cachedContext, cachedClassName]
93-
type RenderCache = [
94-
object, // prevProps
95-
DefaultTheme | undefined, // prevTheme
96-
StyleSheet, // prevStyleSheet
97-
Stringifier, // prevStylis
98-
number, // prevPropsKeyCount
99-
object, // cachedContext
100-
string, // cachedClassName
101-
ComponentStyle, // prevComponentStyle (for HMR invalidation)
102-
];
103-
10471
function resolveContext<Props extends BaseObject>(
10572
attrs: Attrs<React.HTMLAttributes<Element> & Props>[],
10673
props: ExecutionProps & Props,
@@ -235,60 +202,21 @@ function useStyledComponentImpl<Props extends BaseObject>(
235202
const theme =
236203
determineTheme(props, contextTheme, defaultProps) || (IS_RSC ? undefined : EMPTY_OBJECT);
237204

238-
let context: React.HTMLAttributes<Element> & ExecutionContext & Props;
239-
let generatedClassName: string;
240-
241-
// Client-only render cache: skip resolveContext and generateAndInjectStyles
242-
// when props+theme haven't changed. propsForElement is always rebuilt since
243-
// it's mutated with className/ref after construction.
244-
// __SERVER__ and IS_RSC are build/module-level constants for dead-code elimination.
245-
if (!__SERVER__ && !IS_RSC) {
246-
const renderCacheRef = React.useRef<RenderCache | null>(null);
247-
const prev = renderCacheRef.current;
248-
249-
if (
250-
prev !== null &&
251-
prev[1] === theme &&
252-
prev[2] === ssc.styleSheet &&
253-
prev[3] === ssc.stylis &&
254-
prev[7] === componentStyle &&
255-
shallowEqualContext(prev[0], props, prev[4])
256-
) {
257-
context = prev[5] as typeof context;
258-
generatedClassName = prev[6];
259-
} else {
260-
context = resolveContext<Props>(componentAttrs, props, theme);
261-
generatedClassName = componentStyle.generateAndInjectStyles(
262-
context,
263-
ssc.styleSheet,
264-
ssc.stylis
265-
);
266-
let propsKeyCount = 0;
267-
for (const key in props) {
268-
if (hasOwn.call(props, key)) propsKeyCount++;
269-
}
270-
renderCacheRef.current = [
271-
props,
272-
theme,
273-
ssc.styleSheet,
274-
ssc.stylis,
275-
propsKeyCount,
276-
context,
277-
generatedClassName,
278-
componentStyle,
279-
];
280-
}
281-
} else {
282-
context = resolveContext<Props>(componentAttrs, props, theme);
283-
generatedClassName = componentStyle.generateAndInjectStyles(
284-
context,
285-
ssc.styleSheet,
286-
ssc.stylis
287-
);
288-
}
205+
// Interpolations and attr functions run on every render. They are this
206+
// component's own user code and may call hooks or read inputs outside
207+
// (props + theme), so skipping their evaluation across renders breaks the
208+
// rules of hooks (a hook count that changes between renders) and serves stale
209+
// styles (#5788). The pure work downstream of the produced CSS string
210+
// (hashing, compile, injection) is already memoized inside ComponentStyle; a
211+
// props-equal re-render bailout belongs at the component boundary via
212+
// React.memo, which only the caller can key correctly.
213+
const context = resolveContext<Props>(componentAttrs, props, theme);
214+
const generatedClassName = componentStyle.generateAndInjectStyles(
215+
context,
216+
ssc.styleSheet,
217+
ssc.stylis
218+
);
289219

290-
// Outside the render-cache branch: a hook skipped on a cache hit is a hook
291-
// count that changes between renders, which React rejects outright (#5788).
292220
if (process.env.NODE_ENV !== 'production' && React.useDebugValue) {
293221
React.useDebugValue(generatedClassName);
294222
}

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

Lines changed: 8 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -23,21 +23,6 @@ import isStyledComponent from '../utils/isStyledComponent';
2323
import merge from '../utils/mixinDeep';
2424
import { DefaultTheme, ThemeContext } from './ThemeProvider';
2525

26-
const hasOwn = Object.prototype.hasOwnProperty;
27-
28-
function shallowEqualContext(prev: object, next: object, prevKeyCount: number): boolean {
29-
const a = prev as Record<string, unknown>;
30-
const b = next as Record<string, unknown>;
31-
let nextKeyCount = 0;
32-
for (const key in b) {
33-
if (hasOwn.call(b, key)) {
34-
nextKeyCount++;
35-
if (a[key] !== b[key]) return false;
36-
}
37-
}
38-
return nextKeyCount === prevKeyCount;
39-
}
40-
4126
function resolveContext<Props extends object>(
4227
theme: DefaultTheme = EMPTY_OBJECT,
4328
props: Props,
@@ -80,9 +65,6 @@ function buildPropsForElement(
8065
return propsForElement;
8166
}
8267

83-
// [prevProps, prevTheme, prevPropsKeyCount, cachedContext, cachedStyles]
84-
type RenderCache = [object, DefaultTheme | undefined, number, object, any];
85-
8668
function useStyledComponentImpl<Props extends StyledComponentImplProps>(
8769
forwardedComponent: IStyledComponent<'native', Props>,
8870
props: Props,
@@ -100,25 +82,14 @@ function useStyledComponentImpl<Props extends StyledComponentImplProps>(
10082
const contextTheme = React.useContext ? React.useContext(ThemeContext) : undefined;
10183
const theme = determineTheme(props, contextTheme, defaultProps) || EMPTY_OBJECT;
10284

103-
let context: ExecutionContext & Props;
104-
let generatedStyles: any;
105-
106-
const renderCacheRef = React.useRef ? React.useRef<RenderCache | null>(null) : { current: null };
107-
const prev = renderCacheRef.current;
108-
109-
if (prev !== null && prev[1] === theme && shallowEqualContext(prev[0], props, prev[2])) {
110-
context = prev[3] as typeof context;
111-
generatedStyles = prev[4];
112-
} else {
113-
context = resolveContext<Props>(theme, props, componentAttrs);
114-
generatedStyles = inlineStyle.generateStyleObject(context);
115-
116-
let propsKeyCount = 0;
117-
for (const key in props) {
118-
if (hasOwn.call(props, key)) propsKeyCount++;
119-
}
120-
renderCacheRef.current = [props, theme, propsKeyCount, context, generatedStyles];
121-
}
85+
// Interpolations and attr functions run on every render: they are this
86+
// component's own user code and may call hooks or read inputs outside
87+
// (props + theme), so skipping their evaluation across renders breaks the
88+
// rules of hooks and serves stale styles (#5788). generateStyleObject returns
89+
// a stable style reference for equal CSS via InlineStyle's own cache, so the
90+
// style useMemo below keeps a stable identity without an outer render cache.
91+
const context = resolveContext<Props>(theme, props, componentAttrs);
92+
const generatedStyles = inlineStyle.generateStyleObject(context);
12293

12394
const elementToBeCreated: NativeTarget = (context as any).as || props.as || target;
12495
const propsForElement = buildPropsForElement(context, elementToBeCreated, shouldForwardProp);

0 commit comments

Comments
 (0)