Paweł Krystkiewicz
All articles

8 min read

The theme hook doing 440 deep merges per render

After a minor library update, a team’s table became unusably slow. Memoizing the css prop helped only a little. The real issue was useTheme() deep-merging the entire token tree on every call.

We shipped a minor release of our component library, and a team building on it reported that their table had become slow. Initial load was sluggish, adding rows was laggy, and their test suite had started timing out.

Our first attempt was to memoize the css prop objects used in the table cells. In a focused benchmark on a single cell type, this made re-renders about 21% faster. Load time didn’t improve at all.

The real cost was one layer deeper. Every cell and every row called our useTheme() hook twice, and each call ran a deep merge over the entire design token tree. A 20 × 10 table means 200 cells and 20 rows, so 440 deep merges per render.

What changed

Between those two minor versions, the table had moved from static styled-components templates to styles built from design tokens at render time. Each cell now read the current theme and constructed a style object for the css prop. This added two costs: a theme lookup per cell, and a fresh style object on every render.

We addressed the style object problem first. It was the smaller contributor.

How the css prop actually works

Our initial diagnosis was that a new object on every render caused styled-components to regenerate styles, so we should memoize it. That assumption was wrong.

Thanks to babel-plugin-styled-components, a css prop is converted into a styled component at build time. This component:

jsx
const InlineCell = ({ width }) => {
  const css = { width: `${width}px`, display: 'flex', padding: '0 8px' }; // new object every render
  return <td css={css}>x</td>;
};

compiles to:

js
var _StyledTd = _styled("td").withConfig({
  displayName: "demo___StyledTd",
  componentId: "sc-173h7tb-0"
})(["", ""], p => p.$_css);

The object is passed down as a transient prop $_css. The only rule in the generated component is a function that returns whatever was passed in.

In styled-components 6.1.19, ComponentStyle.generateAndInjectStyles runs on every render. For dynamic styles it flattens the object into a CSS string, hashes it, and only injects a new rule if the hash hasn’t been seen before:

ts
const partString = joinStringArray(flatten(partRule, executionContext, styleSheet, stylis));
dynamicHash = phash(dynamicHash, partString + i);
css += partString;
// ...
const name = generateName(dynamicHash >>> 0);
if (!styleSheet.hasNameForId(this.componentId, name)) {
  styleSheet.insertRules(this.componentId, name, stylis(css, `.${name}`, undefined, this.componentId));
}

The generated class name depends on the content of the styles. The same values produce the same class name whether the object is new or memoized. A memoized object still gets flattened and hashed on every render. Only new content runs stylis and inserts a rule.

I rendered 2,000 cells with 20 distinct widths in jsdom: 20 rules injected on mount, zero more after 15 re-renders, and every cell kept its class. Changing a single width added exactly one new rule. Memoizing or not made no difference to the final stylesheet.

So useMemo only saves the cost of creating the object itself. That’s not nothing: it gave us 10–25% faster re-renders in the 2,000-cell test, depending on which variant ran first, and improved our benchmark on a cell shaped like the real one from 24.8 ms to 19.5 ms. But it was still just a re-render optimization, and the table was slow to mount in the first place.

React.memo performed much better (3.1 ms in the benchmark), but only when props were stable. react-table’s flexRender passes a fresh children element on every render, so the memoization was defeated in real usage.

The hook

Here’s the essential problem, reduced to a minimal version written for this article:

jsx
const ThemeContext = createContext({});
// combine(raw) deep-merges the library's tokens into raw

// before: merge on every call
const useThemeSlow = () => combine(useContext(ThemeContext));

// after: one merge per distinct provider value
const cache = new WeakMap();
const useThemeCached = () => {
  const raw = useContext(ThemeContext);
  let theme = cache.get(raw);
  if (!theme) { theme = combine(raw); cache.set(raw, theme); }
  return theme;
};

Our real implementation used MUI’s createTheme(theme, tokens), which does a recursive deep merge. The original hook did have an early-return path for themes that had already been merged, but the common cases bypassed it: a raw theme coming from an upstream provider, or no provider at all (in which case MUI returns its default theme object). Every call returned a new object, which also broke any useMemo calls downstream that depended on theme values.

The WeakMap approach ensures we perform one merge per distinct theme object and then hand out the same reference to every consumer. Because it’s keyed on the raw theme itself, a new theme produces a new merged result, and old entries are automatically cleaned up when the original theme is garbage-collected.

In a stripped-down benchmark made for this article, with 100 consumers and a synthetic token tree of roughly 2,400 leaves, we went from 100 merges and a 25 ms mount to 1 merge and under 1 ms. Our real bench went from 100 distinct theme objects and a 1,098 ms mount to 1 object and 14.4 ms.

We then measured the actual table cells and rows from each release: a 20 × 10 grid, with the real babel-compiled css prop, running in jsdom against React 19 dev, three runs each, with an upstream theme in the provider:

ReleaseMountRe-renderMerges per re-render
Before the regression14.5–17 ms11–12 ms0
Regressed5.2–5.5 s5.2–5.4 s440
Hook cache30–32 ms12 ms0
Hook cache + css memo29–31 ms11–12 ms0

The jsdom numbers are inflated, but the ratios tell the story. The theme cache eliminated the regression. Mount time sits roughly 15 ms above the original release, about the cost of the single remaining merge. On the full table the additional css memoization was lost in the noise.

Old copies don’t get your fix

Weeks after we shipped the cached hook, a production performance trace still showed deep merging near the top of the Bottom-up view. The cost was flat across the entire recording, with allocation to match. That meant it was running on every render, not on some event.

The minified code in the trace had no cache. The application was a micro-frontend that bundled its own older copy of our library. With module federation, each remote can ship its own version, so an old copy never receives your fix.

We solved this by moving the merge into the provider. That way even old copies of the hook see an already-merged theme and skip their work. This only works if the old hook and the new provider read from the same context instance, which in a module-federation setup means sharing the theme library as a singleton: here MUI, plus the @emotion/react it keeps the theme context in. A remote that bundles its own copy reads its own context and never sees your provider.

jsx
const isMerged = (theme) => theme.tokens !== undefined; // a key only our merge adds

// an old bundled copy of the hook: no cache, but it skips themes that are already merged
const useThemeOldCopy = () => {
  const theme = useContext(ThemeContext);
  return isMerged(theme) ? theme : combine(theme);
};

const MergingProvider = ({ theme, children }) => {
  const merged = useMemo(() => combine(theme), [theme]);
  return <ThemeContext.Provider value={merged}>{children}</ThemeContext.Provider>;
};

The isMerged check looks for a property that only our merge adds. Keys that MUI itself sets (like components) are present on its default theme, so they don’t work as markers. In the minimal version, 100 consumers on the old copy drop from 100 merges to 1, the provider’s own. In the real code, under a provider holding a pre-merged theme, the regressed table mounted in 17.5 ms with zero merges, down from 5.2 s.

The lesson is to fix the problem at the boundary that every copy shares, rather than inside code that each bundle might copy.

A provider that creates a new object

One issue remains. In @mui/material 5.18.0, ThemeProvider does this on every render when the theme has no vars (the common case for a plain createTheme()):

js
finalTheme = { ...themeInput, vars: null };

React uses Object.is to decide whether a provider value has changed. A new object means every consumer re-renders, even those wrapped in React.memo. The minimal version, and the fix if the provider is yours:

jsx
const SpreadingProvider = ({ theme, children }) => (
  <ThemeContext.Provider value={{ ...theme, vars: null }}>{children}</ThemeContext.Provider>
);

const StableProvider = ({ theme, children }) => {
  const value = useMemo(() => ({ ...theme, vars: null }), [theme]);
  return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
};

When the parent re-renders, the spreading version causes all 100 memoized consumers to re-render and triggers one merge through the WeakMap (a new object is a new key). The memoized version re-renders none of them and performs zero merges.

MUI’s provider behaves like the spreading version. I checked with 100 memoized consumers: one parent re-render, 100 consumer re-renders. With the hook cache, that’s one merge per provider render. With an already-merged theme in context, zero merges. The 100 re-renders stay either way. Keep MUI’s ThemeProvider outside of frequently changing state.

What we do to prevent regressions

We added unit tests that verify every consumer receives the same theme reference, that the reference survives a real in-tree re-render, that a new theme produces a new reference, and that merging twice yields an identical result to merging once.

We also have manual performance benches that assert a single distinct theme object across 100 consumers. They run manually, not in CI. Yes, I know.

The table stories include a Storybook performance panel, though we don’t have a lint rule.

How to find this in your own app

  1. In the React DevTools Profiler, enable “Record why each component rendered while profiling.” If many components say “Context changed” after an interaction that didn’t touch the theme, your provider value isn’t stable.

  2. In a Chrome performance trace, search the Bottom-up tab for createTheme, deepmerge, or your merge function. Flat cost across the recording means it’s running on every render.

  3. In a test, render N consumers, collect the results of useTheme() in a Set, and assert that the set has size 1.

  4. Never construct a theme inline inside a provider. Create it once at module scope or in a useMemo with the correct dependencies.

  5. When using module federation with a shared theme context, fix the problem at the provider boundary so older bundled copies benefit automatically.

  6. Don’t rely on useMemo around a css object to save styled-components work. Reduce renders instead, or move static styles into a styled template.

For this particular table, building the theme once was essentially the entire fix. The original css memoization was worth only a few milliseconds.