Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
  }))
)
like image 698
Polisas Avatar asked Mar 04 '17 01:03

Polisas


2 Answers

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

like image 160
Fabian Schultz Avatar answered Nov 14 '22 08:11

Fabian Schultz


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

like image 8
Greg Avatar answered Nov 14 '22 09:11

Greg