1.0.0 • Published 5 years ago
hook-to-props v1.0.0
🚢hookToProps
Use hooks like higherOrders:
class DisplayWindowSize extends React.Component {
// ...
render() {
this.props.windowSize
}
}
const useHooks = () => ({ windowSize: useWindowSize() }))
export default hookToProps(useHooks)(DisplayWindowSize)
Under the hood
// That's the entire source code, really.
const hookToProps = useHooks => Component => {
const HookResultProvider = props => <Component {...props} {...useHooks(props)} />
return HookResultProvider
}
export default hookToProps
useHooks
is a custom hook used to format (or combine) the result of hook calls. It should return an object. HookProvider
is a functional Higher-Order-Component. It calls useHooks
and spreads the result as a prop.
(The fact that the hook calls in useHooks
are only executed when useHooks
is called is known as lazy evaluation. A function used to inject code into another component is also known as a Thunk.)
More Examples
Using multiple hooks:
class WindowDetails extends React.Component {
// ...
render() {
this.props.windowSize + ' ' + this.props.scrollPosition
}
}
const useHooks = () => {
const windowSize = useWindowSize()
const scrollPosition = useWindowScrollPosition()
return { windowSize, scrollPosition }
}
export default hookToProps(useHooks)(WindowDetails)
Using props with hooks:
class SearchResults extends React.Component {
// ...
render() {
this.props.isLoading ? 'loading' : this.props.searchResults
}
}
const useHooks = props => {
const [isLoading, searchResults] = useFetch(
`https://foo.com/?search=${props.searchTerm}`
)
return { isLoading, searchResults }
}
export default hookToProps(useHooks)(WindowDetails)
1.0.0
5 years ago