hook-hoc

Use React hooks with your class components by Higher Order Component

Usage no npm install needed!

<script type="module">
  import hookHoc from 'https://cdn.skypack.dev/hook-hoc';
</script>

README

Hook Higher Order Component (HOC)

CircleCI Coverage Status npm downloads gzip size npm version PRs Welcome

Use React hooks with your class components by Higher Order Component.

Warning:

This is intended to help incrementally transition large existing class components to hooks. Please write new components using functions!

Data fetching Example

Let's fetch some data using Rest Hooks. We use the provided id prop to know what to fetch, then inject user and friends by returning an object with those props.

import withHook from 'hook-hoc';
import { useResource } from 'rest-hooks';

import UserResource from 'resources/user';

const useProfile = ({ id }: { id: number }) => {
  const user = useResource(UserResource.detail(), { id });
  const friends = useResource(UserResource.list(), { id });
  return { user, friends };
};

class Profile extends React.PureComponent<{
  id: number;
  user: UserResource;
  friends: UserResource[];
}> {
  //...
}

export default withHook(useProfile)(Profile);

Forms Example

Here's an example of using a theoretical forms handling library

import React from 'react';
import withHook from 'hook-hoc';
import { useFields, FormValues } from '@cb/forms';

import SignupForm from './SignupForm';

// export this for testing if needed
export function useSignupFields() {
  const fields = useFields(SignupForm);
  const [submit] = useSubmitter(SignupForm);
  return { ...fields, submit };
}

type Props = FormValues<SignupForm> & {
  submit: (options?: object) => Promise<any>;
};

class SignupFields extends React.PureComponent<Props> {
  render() {
    const { submit, username, password } = this.props;

    return (
      <form
        onSubmit={e => {
          e.preventDefault();
          submit();
        }}
      >
        <InputField {...username} />
        <InputField {...password} type="password" />
        <button type="submit">SignUp</button>
      </form>
    );
  }
}
export default withHook(useSignupFields)(SignupFields);