4

If I have an HOC takes some context and passes down helpers functions based on that context, is that abuse of an HOC? Essentially it is the same thing as just utilizing a helper class.

For example:

import helpers from './helpers'

function withHelpers(WrappedComponent, context) {
  return class extends React.Component {
    render() {
      let contextualHelpers = {...// bind all helpers to context}

      return (
        <WrappedComponent {...this.props} {...contextualHelpers} />
      )
    }
  }
}

Am I better off just have a helper class in this case since I am not utilizing any lifecycle methods, state, etc. what the HOC is providing? Then instead of calling withHelpers inside the consuming component I would just instantiate the helper with the context in the constructor this.helper = new Helper(context).

In other words, is this abusing the HOC concept?

Adam Thompson
  • 3,278
  • 3
  • 22
  • 37

2 Answers2

4

This is possibly an antipattern because Helper and component instance aren't related. Moreover, a HOC may result in unnecessary overhead if Helper doesn't need to be instantiated on each render while it's instantiated inside render.

In this case the only benefit from a HOC is that it implements dependency injection pattern by injecting dependencies via props. If wrapped component cannot benefit from dependency injection (improved reusability and testability), a HOC can be considered an antipattern.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
2

No, you're not abusing HOC concept, but, what exactly does HOC help you with in this case? Do you want to be able to have these helpers in a lot of components? If so, you can just simply instantiate the helpers as you mentioned.

Keep in mind that HOCs make your components less readable, as you would have to read all of the component to find out where are these helpers instantiated (in this case, other developers would have to read all of the file to reach out the final line and see export default withHelpers(FooComponent, context)!

So you're just better off with instantiating the helpers within your constructor or even componentDidMount.

Masious
  • 431
  • 5
  • 14