February 06, 2019 | 2 minutes read

Recompose but with React Hooks!

#react#javascript#package#library

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

1npm install re-enhance
1yarn add re-enhance

Usage

1import { pipe, usePropMapper, useStateEnhancer /* ... */ } from 're-enhance'

Recompose

1const BaseComponent = props => {...}
2
3const enhance = compose(
4 withState(/*...args*/),
5 mapProps(/*...args*/),
6 pure
7)
8const EnhancedComponent = enhance(BaseComponent)

Re-Enhance

1const useEnhancer = pipe(
2 useStateEnhancer(/*...args*/),
3 usePropMapper(/*...args*/),
4 /*pure cannot be hooked 😔*/
5)
6
7// But you can use memo!
8const BaseComponent = React.memo(props => {
9 const enhancedProps = useEnhancer(props)
10 // ...
11})

Example

1import React from 'react';
2import { pipe, useHandlers, useStateEnhancer } from 're-enhance';
3
4const useEnhancer = pipe(
5 useStateEnhancer('counter', 'setCounter', 0),
6 useHandlers({
7 inc: ({ setCounter }) => () => setCounter(counter => counter + 1),
8 dec: ({ setCounter }) => () => setCounter(counter => counter - 1),
9 }),
10);
11
12function Component(props) {
13 const { counter, inc, dec } = useEnhancer(props);
14 return (
15 <div>
16 <button onClick={inc}>Inc</button>
17 {counter}
18 <button onClick={dec}>Dec</button>
19 </div>
20 );
21}
22
23export default Component;

Feedback wanted

Due to the limitations of Hooks,

1recompose
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