Skip to content

Commit

Permalink
Add a basic catch and warning for anonymous/non-static functions crea…
Browse files Browse the repository at this point in the history
…ting map entries every rerender
  • Loading branch information
cee-chen committed Feb 14, 2024
1 parent 3c4fdee commit 2c95aec
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/services/theme/style_memoization.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
import React, { useState } from 'react';
import { css } from '@emotion/react';
import { fireEvent } from '@testing-library/react';
import { render } from '../../test/rtl';
import { render, renderHook } from '../../test/rtl';
import { testOnReactVersion } from '../../test/internal';

import type { UseEuiTheme } from './hooks';
import { EuiThemeProvider } from './provider';
Expand Down Expand Up @@ -70,4 +71,15 @@ describe('useEuiMemoizedStyles', () => {
);
expect(componentStyles).toHaveBeenCalledTimes(2);
});

testOnReactVersion(['18'])(
'throws an error if passed anonymous functions',
() => {
expect(() =>
renderHook(() => useEuiMemoizedStyles(() => ({})))
).toThrowError(
'Styles are memoized per function. Your style functions must be statically defined in order to not create a new map entry every rerender.'
);
}
);
});
5 changes: 5 additions & 0 deletions src/services/theme/style_memoization.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,11 @@ export const useEuiMemoizedStyles = <
const euiThemeContext = useEuiTheme();

const memoizedComponentStyles = useMemo(() => {
if (!styleGenerator.name) {
throw new Error(
'Styles are memoized per function. Your style functions must be statically defined in order to not create a new map entry every rerender.'
);
}
const existingStyles = memoizedStyles.get(styleGenerator);
if (existingStyles) {
return existingStyles;
Expand Down

0 comments on commit 2c95aec

Please sign in to comment.