I've been looking at react recompose library and trying to grasp difference here, result is the same, tried to read docs, but got even more confused, why there is two ways to do same thing ?
const enhance = compose(
withState('counter', 'setCounter', 0),
withHandlers({
increment: props => () => props.setCounter(n => n + 1),
decrement: props => () => props.setCounter(n => n - 1)
})
)
const enhance = compose(
withState('counter', 'setCounter', 0),
withProps(({ setCounter }) => ({
increment: () => setCounter(n => n + 1),
decrement: () => setCounter(n => n - 1)
}))
)
It's mostly performance related, as withHandlers
doesn't create a new function every render. From a related Github issue:
withProps
will create new functions every time when it get updated; on the other hand,withHandlers
won't create new functions.
withHandlers
is useful when you want to pass these functions to other components whichshouldComponents
are implemented by comparing props shallowly (like howrecompose/pure
do).
Additionally to Fabian Schultz' answer, note that withProps
can be used to add any type of prop, while withHandlers
can only add functions.
So when you add functions, use withHandlers
when possible, for performance. When you add anything else, use withProps
(or mapProps
if you want to remove all other props).
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