HOC for React Query

It turns out that React Query by default uses hooks approach. If you need to access some part of library inside your class components you can use Render Props pattern. What if you can’t use it? Below you will find High Order Component that injects queryClient into WrappedComponent.

interface WithReactQueryClientProps {
  queryClient: QueryClient;

function withReactQueryClient<T extends WithReactQueryClientProps>(
  WrappedComponent: React.ComponentType<T>,
) {
  const displayName =
    WrappedComponent.displayName || WrappedComponent.name || "Component";

  const ComponentWithReactQueryClient = (
    props: Omit<T, keyof WithReactQueryClientProps>,
  ) => {
    const queryClient = useQueryClient();

    return <WrappedComponent {...(props as T)} queryClient={queryClient} />;

  ComponentWithReactQueryClient.displayName = `withReactQueryClient(${displayName})`;

  return ComponentWithReactQueryClient;