Home > Blockchain >  How to properly use HOC with Hooks?
How to properly use HOC with Hooks?

Time:08-12

What is the best way to use HOC if I need to get data from a hook?

I have two options:

  1. Pass the received data from the hook as a parameter to the HOC

HOC:

export const withAuth = (
  isAuth: boolean,
  {
    ComponentForAuthorized,
    ComponentForUnauthorized,
  }: {
    ComponentForAuthorized: () => JSX.Element;
    ComponentForUnauthorized: () => JSX.Element;
  }
) => {
  const WrappedComponent = (props: any) => {
    if (isAuth) return <ComponentForAuthorized {...props} />;
    else return <ComponentForUnauthorized {...props} />;
  };

  return WrappedComponent;
};

And use like this:

export const Sidebar = () => {
  const { token } = useJWT();
  const AccountComponent = withAuth(Boolean(token), {
    ComponentForAuthorized: AccountBlock,
    ComponentForUnauthorized: LoginButton,
  });

  return (
      <AccountComponent />
  );
};
  1. Call hook in HOC

HOC:

export const withAuth =
  (
    ComponentForAuthorized: () => JSX.Element,
    ComponentForUnauthorized: () => JSX.Element
  ) =>
  (props: any) => {
    const { token } = useJWT();

    const WrappedComponent = () => {
      if (Boolean(token)) return <ComponentForAuthorized {...props} />;
      else return <ComponentForUnauthorized {...props} />;
    };

    return WrappedComponent();
  };

Are there any recommendations or best practices?

CodePudding user response:

Best practice is to avoid using HOCs to wrap components and instead rewrite the HOC functionality as custom hooks and import those into the components.

https://kentcdodds.com/chats/01/03/realigning-your-model-of-react-after-hooks-with-dan-abramov

CodePudding user response:

if you must use HOC.

Pass the received data from the hook as a parameter to the HOC

It May be easy to Test with dependency injection

But you should probably use a custom hook as Luke Storry suggested.

  • Related