DEV Community

Cristian Velasquez Ramos
Cristian Velasquez Ramos

Posted on

Recompose but with React Hooks!

Hooks

When hooks were announced, I immediately looked to the library recompose to see if it was going to be updated with some hooks.

Unfortunately, the library was to be discontinued..

I decided to take the patterns of Recompose and translate them using Hooks.

The result: Re-Enhance

npm install re-enhance 
Enter fullscreen mode Exit fullscreen mode
yarn add re-enhance 
Enter fullscreen mode Exit fullscreen mode

Usage

import { pipe, usePropMapper, useStateEnhancer /* ... */ } from 're-enhance' 
Enter fullscreen mode Exit fullscreen mode

Recompose

const BaseComponent = props => {...} const enhance = compose( withState(/*...args*/), mapProps(/*...args*/), pure ) const EnhancedComponent = enhance(BaseComponent) 
Enter fullscreen mode Exit fullscreen mode

Re-Enhance

const useEnhancer = pipe( useStateEnhancer(/*...args*/), usePropMapper(/*...args*/), /*pure cannot be hooked 😔*/ ) // But you can use memo! const BaseComponent = React.memo(props => { const enhancedProps = useEnhancer(props) // ... }) 
Enter fullscreen mode Exit fullscreen mode

Example

import React from 'react'; import { pipe, useHandlers, useStateEnhancer } from 're-enhance'; const useEnhancer = pipe( useStateEnhancer('counter', 'setCounter', 0), useHandlers({ inc: ({ setCounter }) => () => setCounter(counter => counter + 1), dec: ({ setCounter }) => () => setCounter(counter => counter - 1), }), ); function Component(props) { const { counter, inc, dec } = useEnhancer(props); return ( <div> <button onClick={inc}>Inc</button>  {counter} <button onClick={dec}>Dec</button>  </div>  ); } export default Component; 
Enter fullscreen mode Exit fullscreen mode

Feedback wanted

Due to the limitations of Hooks, recompose could not be totally ported using React Hooks. However, I may add some of the HOC's to this project for convenience!

If you think that more Hooks can be added, feel free to contribute! 🎉🎉

Check it out!

Re-Enhance

Top comments (0)