Skip to content

Instantly share code, notes, and snippets.

@jul-sh
Last active February 9, 2019 19:04
Show Gist options
  • Save jul-sh/12bf0c7143d20e58c1d803d1fb14955d to your computer and use it in GitHub Desktop.
Save jul-sh/12bf0c7143d20e58c1d803d1fb14955d to your computer and use it in GitHub Desktop.
connectHooks

I'm not sure a HoC for hooks is a good idea, but it seemed fun to build. Also, it may come in handy when adding new code to old components.

Use like so:

export default connectHooks([
  {
    hook: useFetch,
    hookArgs: ["https://swapi.co/api/people/1"],
    toProps: ([isLoading, data]) => ({ isLoading, data })
  }
])(
  class ClassComponent extends React.Component {
   // ...
   render () {
     this.props.isLoading ? "loading" : this.props.data
   }
  }
)

example: https://codesandbox.io/s/qk6r33649q

Compose hooks into higherOrders like so:

const withWindowSizeAndScrollPosition = connectHooks([
  {
    hook: useWindowScrollPosition,
    toProps: scrollPosition => ({ scrollPosition })
  },
  {
    hook: useWindowSize,
    toProps: windowSize => ({ windowSize })
  }
])
import React from "react"
const connectHooks = hooks => Component => props => {
const HookProvider = ({ hooks, Component }) => (
<Component
{...props}
{...hooks.reduce(
(accumulator, { hook, hookArgs, toProps }) => ({
...accumulator,
...toProps(hook(...hookArgs))
}),
{}
)}
/>
)
return <HookProvider hooks={hooks} Component={Component} />
}
export default connectHooks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment