Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React HOCs vs Helper Classes?

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?

like image 905
Adam Thompson Avatar asked Oct 20 '25 07:10

Adam Thompson


1 Answers

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.

like image 194
Estus Flask Avatar answered Oct 22 '25 21:10

Estus Flask



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!