Polisas
Polisas

Reputation: 541

WithProps vs withHandlers

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)
  }))
)

Upvotes: 5

Views: 4641

Answers (2)

Greg
Greg

Reputation: 3568

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).

Upvotes: 8

Fabian Schultz
Fabian Schultz

Reputation: 18546

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 which shouldComponents are implemented by comparing props shallowly (like how recompose/pure do).

Upvotes: 9

Related Questions