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?
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