Memoize "withPropsFrom" HOC

This commit is contained in:
schroda
2024-12-21 14:13:31 +01:00
parent 34ad331a71
commit f1f660a546

View File

@@ -6,7 +6,7 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/ */
import { ComponentType, forwardRef } from 'react'; import { ComponentType, forwardRef, memo } from 'react';
type PropsSourceCreator<T> = () => T; type PropsSourceCreator<T> = () => T;
@@ -19,6 +19,7 @@ export const withPropsFrom = <
propsSources: { [K in keyof SourceProps]: PropsSourceCreator<SourceProps[K]> }, propsSources: { [K in keyof SourceProps]: PropsSourceCreator<SourceProps[K]> },
sourcePropKeys: SourcePropKeys[], sourcePropKeys: SourcePropKeys[],
) => ) =>
memo(
forwardRef<HTMLElement, Omit<ComponentProps, SourcePropKeys>>((props, ref) => { forwardRef<HTMLElement, Omit<ComponentProps, SourcePropKeys>>((props, ref) => {
const sourceProps = propsSources.reduce((acc, propsSource) => ({ ...acc, ...propsSource() }), {}); const sourceProps = propsSources.reduce((acc, propsSource) => ({ ...acc, ...propsSource() }), {});
@@ -29,4 +30,5 @@ export const withPropsFrom = <
const combinedProps = { ...props, ...selectedProps } as unknown as ComponentProps; const combinedProps = { ...props, ...selectedProps } as unknown as ComponentProps;
return <Component {...combinedProps} ref={ref} />; return <Component {...combinedProps} ref={ref} />;
}); }),
);