- Passing children and returning children with additional logic
const WithLoadingState =(props)=> {
// Handle display the spinner, error message etc
if(!props.error) return props.children
}
- Actual
HOC
component
const withLoadingState =(Component) => (props)=> {
// Additional logics here, display spinner, error message etc.
if(!props.error) return <Component {...props} />
}
For the above 2 components, I think they do achieve the same results. The first one, I am not sure what it’s called. But, that first component seems way simpler and cleaner to implement.
Second component
is what they call HOC
and is more complicated and harder to use. So, I was wondering, why people use HOC
component whereas the First Component
can bascially achieve the same thing.
The obstacle I came across with HOC
is, we have to call it outside of the React Component
. We can call inside the React Component itself
. But, IMO, it’s ugly.
Usage
- Component One (1)
const MyData =()=>
<WithLoadingState>
<MyList />
</WithLoadingState>
- HOC Component
const MyData =()=> withLoadingState(MyList)
Or
const MyListWithLoadingState = withLoadingState(MyList)
const MyData =()=> <MyListWithLoadingState />
What are the differences and what benefits does HOC component
offer?