React: React hooks in HOC

Created on 11 Oct 2019  路  1Comment  路  Source: facebook/react

I have a pattern question.

I'm thinking of using a pattern where I extract my logic in higher-order components, so components are actually "dumb".

So instead of

const Signup = props => {
  const [onSubmit, {data}] = useMutation (SIGNUP_GQL)
  return (
    ...
  )
}
export default Signup

I'll do

const withMutation = gql => C => props => {
   const [onSubmit, {data}] = useMutation (SIGNUP_GQL)
   return <C onSubmit={onSubmit} data={data} />
}

once, and then just

const Signup = ({onSubmit, data}) => (
  ...
)
export default withMutation (SIGNUP_GQL) (Signup)

So far I haven't encountered any problems (up to many typo's 馃槈). However, the docs say that hooks can only be called inside the body of a functional component. So my question is whether withMutation (..) (..) count as a functional component for this definition.

And in general the question is whether react hooks have full support in HOC. My naive understanding is that those two approaches should be fundamentally equivalent regardless of the implementation. But I want to make sure, and if they aren't, whether the developers plan to support HOCs going forward. I am structuring my whole project this way, so that's why this is important to me. And I haven't read the hooks implementation, so not versed in how it works.

Cheers. 馃檪

Most helpful comment

Yes, this is fine. Higher-order components are not components, but if you return a function component from a HOC, you can use hooks their. So, your example is fine, but this is not:

const withMutation = gql => C => {
   const [onSubmit, {data}] = useMutation (SIGNUP_GQL); // <-- outside of the component

   return props => {
     return <C onSubmit={onSubmit} data={data} />
  };
}

>All comments

Yes, this is fine. Higher-order components are not components, but if you return a function component from a HOC, you can use hooks their. So, your example is fine, but this is not:

const withMutation = gql => C => {
   const [onSubmit, {data}] = useMutation (SIGNUP_GQL); // <-- outside of the component

   return props => {
     return <C onSubmit={onSubmit} data={data} />
  };
}
Was this page helpful?
0 / 5 - 0 ratings