I'm trying to write reusable hoc for handling context data and prevent unecessary re-renders. It works alright but I have problem with typescript. Not sure if it is because my generic types in hoc or should I somehow give different typing in data component. I created sandbox with this problem and would be grateful for some help.
code: hoc
export const withDataContext = <
TProps extends unknown,
TValue extends unknown
>(
Component: ComponentType<TProps & Record<string, TValue>>,
selectors: Record<string, (data: ContextState) => TValue>
) => {
const MemoisedComponent = React.memo(Component) as MemoExoticComponent<
ComponentType<Record<string, TValue>>
>;
return (props: TProps & Record<string, TValue>) => {
const data = useDataContext();
const contextProps = Object.keys(selectors).reduce(
(acc: Record<string, TValue>, key) => {
acc[key] = selectors[key](data);
return acc;
},
{}
);
return <MemoisedComponent {...props} {...contextProps} />;
};
};
components:
type DataComponentProps = {
data: {};
index: number;
};
export const DataComponent = ({
handleFetch,
handleDelete,
data,
index
}: DataComponentProps) => {
console.log(data);
return <p>{index}</p>;
};
export const DataWithSelectors = withDataContext(DataComponent, {
handleFetch: (data) => data.handleFetch,
handleDelete: (data) => data.handleDelete
});
Basically if I add handleFetch and handleDelete to DataComponentProps then I have problem in parent component as I don't pass handleFetch, handleDelete via props. If i remove them from types then I have problem with typing in DataComponent.
https://codesandbox.io/s/great-feather-b86c41?file=/src/dataComponent.tsx:42-472