If you want to write stateless functions in React and need to combine a number of setState
functions to that stateless function.
Enables to compose a number of functions expecting state and props. This enables to reuse functions when needed and
eases testing those functions (as they are standalone and decoupled from React.
// counter.js
import React, {Component} from 'react'
import setStateHigherOrderComponent from './HigherOrderComponents'
// some set state function...
const Inc = () => (state, {step}) =>
({count: state.count + step})
const Dec = () => (state, {step}) =>
({count: state.count - step})
// some stateless function
const SomeStatelessFunction = ({count, inc, dec, ...rest}) => {
return (
<div>
Count: {count}
<button onClick={() => inc()}>Inc</button>
<button onClick={() => dec()}>Dec</button>
</div>
)
}
export default setStateHigherOrderComponent({inc: Inc, dec: Dec}, SomeStatelessFunction)
Now you can use the Counter and define the initialState
as needed.
import React from 'react'
import {render} from 'react-dom'
import CreateCounter from './Counter'
const CounterA = CreateCounter({count: 0})
const CounterB = CreateCounter({count: 10})
const CounterC = CreateCounter({count: 20})
render(<div>
<CounterA step={1} />
<CounterB step={2} />
<CounterC step={3} />
</div>, document.getElementById('app'))
You can choose to switchout Ramda with another library, also you can remove the currying and adapt as needed. This is just a reference implementation.