I have a React component that displays styled text, and I want to have it load a network resource, listen for WebSocket input, and display notifications. In order to do this, I write Higher Order Component wrapper functions for each of these: withResource
, withSocket
, and withNotifications
.
When exporting the component, is this correct?
class TextComponent extends React.Component {
...
}
export default withResource(withSocket(withNotifications(TextComponent)))
You can use compose
from redux or recompose. For example:
import { compose } from 'redux'
export default compose(
withResource,
withSocket,
withNotifications
)(TextComponent)
import { compose } from 'recompose'
export default compose(
withResource,
withSocket,
withNotifications
)(TextComponent)
It's called functional composition and it has mathematical background (that causes y and x variables naming and reversed execution of functions). It decreases complexity of the way how you call written functions by eliminating variables extra definition and deep level of function wrapage.
Write it by yourself or use from a library like: lodash
, rambda
, redux
, etc.
const compose = (...rest) => x => rest.reduceRight((y, f) => f(y), x)
Usage with first class functions:
const increment = (numb) => numb + 1
const multiplyBy = (multiplyNum) => (num) => multiplyNum * num
compose(increment, multiplyBy(3), increment)(4)// 4 > 5 > 15 > 16
Usage with higher order components:
compose(withRouter, withItems, withRefs)(Component)
Another simple solution can be to do this in three steps, simply putting the HOC components on top of each other like this:
const firstHOC = withNotifications(TextComponent);
const secondHOC = withSocket(firstHOC);
export default withResource(secondHOC);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With