I've searched around and after reading some stuff, I still didn't get when I use recompose
branch
over if-else
statement in react or why even use it?
can anyone mention a good source or explain it?
thanks
It can be used instead of if..else
or ternary operator where function composition is preferred. Recompose provides function composition for React components. As other Recompose higher-order components, branch
HOC can be composed with compose
:
const fooPredicate = ({ type }) => (type === 'foo');
const FooHOC = Comp => props => <Comp ...props>Foo</Comp>;
const BarHOC = Comp => props => <Comp ...props type="bar">Bar</Comp>;
const FooOrBarHOC = branch(fooPredicate, FooHOC, BarHOC);
const SomeHOC = compose(BazHOC, FooOrBarHOC);
const SomeExampleComponent = SomeHOC(ExampleComponent);
All functions involved in SomeExampleComponent
are reusable and can be tested and used separately from each other.
In case the case is simple and these functions aren't expected to be used with any component except ExampleComponent
, it can be simplified to:
const SomeExampleComponent = BazHOC(props => (
props.type === 'foo'
? <ExampleComponent ...props>Foo</ExampleComponent>
: <ExampleComponent ...props type="bar">Bar</ExampleComponent>
));
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