DEV Community

loading...

Recompose but with React Hooks!

Cristian Velasquez Ramos
A growing developer with a heart of code. I have a passion for improvement, believing fully in 改善. I'm looking to do what I can with a keyboard at hand. Sorry, don't have any more one-liners 😅
・1 min read

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

Discussion (0)

Forem Open with the Forem app