Skip to content

Instantly share code, notes, and snippets.

@KonradSzwarc
Created May 26, 2021 12:07
Show Gist options
  • Save KonradSzwarc/0765b88d7b9656fc7a1b3f08156dc043 to your computer and use it in GitHub Desktop.
Save KonradSzwarc/0765b88d7b9656fc7a1b3f08156dc043 to your computer and use it in GitHub Desktop.
HOC that allows to use React hooks with class components.
import React, { ReactElement, ComponentType } from 'react';
function withHook<HookReturn extends Record<string, unknown>>(use: () => HookReturn) {
return <Props extends Record<string, unknown>>(
Component: ComponentType<Props & HookReturn>,
): ComponentType<Props> => {
const WrappedComponent = (props: Props): ReactElement<Props & HookReturn> => {
const hookProps = use();
return <Component {...props} {...hookProps} />;
};
WrappedComponent.displayName = Component.displayName || Component.name;
return WrappedComponent;
};
}
export default withHook;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment