Fri, 08/14/2020 - 21:35
Hoc
Example:
function withProducts(WrappedComponent) {
const [products, setProducts] = React.useState([])
return function(props) {
<WrappedComponent {...props} products ={products}/>
}
}
Popular Implementation: Redux, React-Router
Pros
- Multiple HOC can be composed.
Cons
- Prop clash: Props conflict between Hoc function that provide the same prop. During a clash the last HOC would overwrite prop set by preceding HOCs. Similar to method clashing in mixins.
- Component names are prefixed with HOC name. Example
withBehaviour(MySimpleComponent)
. - Added noise when debugging. Too many nested components
Render prop
Example:
render(){
<FetchProducts render={(data) => {
return <ProductList products={data}/>
}} />
}
Popular Implementation: ReactRouter
Pros
- Cleaner than HOC
Cons
- Since render props are like callback, this could create callback hell. However, it is uncommon to have nested render props.
- Closure defined for every render. Can be a minor performance issue.
- Render function as an expression is not a need JSX an can add noise.
Hooks
Example:
function ProductList () {
const [products] = useProductData();
}
Popular Implementation: React
Pros
- Composable
- Nestable
- Are just functions
Authored by
Tags