February 06, 2019 | 2 minutes read
Recompose but with React Hooks!
#react#javascript#package#library
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 => {...}23const enhance = compose(4 withState(/*...args*/),5 mapProps(/*...args*/),6 pure7)8const EnhancedComponent = enhance(BaseComponent)
Re-Enhance
1const useEnhancer = pipe(2 useStateEnhancer(/*...args*/),3 usePropMapper(/*...args*/),4 /*pure cannot be hooked 😔*/5)67// 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';34const 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);1112function 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}2223export default Component;
Feedback wanted
Due to the limitations of Hooks,
could not be totally ported using React Hooks. However, I may add some of the HOC's to this project for convenience!1recompose
If you think that more Hooks can be added, feel free to contribute! 🎉🎉