This is my short-ish reaction to a linked article about ES6 classes used for React Components instead of “old” createClass.

To be honest, I never used this now abandoned approach as I came to React in times when ES6 classes were a thing and it felt exciting to use something new.

It was a somewhat quick realization that classes are a bad thing. For some time I’ve used an alternative approach with react-stamp which is part of a bigger ecosystem of stamps and is driven by a composition. It might look a lot like createClass, but it’s definitely much more. However, the library is not maintained and it has some weird quirks, so I don’t really recommend that.

Instead, I’ve adopted the way of using the recompose library. I am not saying it’s ultimate gun to every solution. In some cases using class syntax might be still necessary, but consider an example like this.

This is a piece of code from an application in making, I am lazy to prepare something more contrived so bear with me. Notice the important part there at the bottom.

By calling compose you are creating a function that can decorate functional or class component.

This alone gives you great power for unit testing when pure component is exported separately without additional logic. This is very powerful if you like to use Storybook to test and showcase your components.

The withState means you don’t need to think about component state any differently when writing your component. You get updater function which you would call instead of setState. It’s a lot cleaner in my opinion.

The withHandlers is a solution for auto binding. Any handlers created with this are automatically bound. And once again you are getting this in props which removes a lot of confusion and in tests, you can easily pass a mock function instead.

You will probably dislike my approach of defining the handler with const separately. This is something I am not sure about by myself. It could be defined directly inside withHandlers call, but that’s too much nesting for my taste.

There is a question of performance. Honestly, I haven’t tested that out yet too much, but I doubt there will be a huge difference in comparison to classes considering that High-Order Components are recommended by Facebook itself.

You might also notice composeWithApollo function there which I am using for GraphQL with Apollo.

As you can see it’s just another compose wrapped function. This reveals important fact that compositions can be nested!