What is the best way to use HOC if I need to get data from a hook?
I have two options:
- 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 />
);
};
- 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?