-
-
Save levity/3ab3e0f88fd28d55fde5444b9d482f98 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// FAIL | |
// the fatal limitation of this approach is that we cannot call | |
// more hooks from inside the `render` method, because that would be | |
// calling hooks from inside hooks, a no-no. | |
// | |
// this component wrapper is for getting props from the store | |
// and ensuring re-renders take place only when the props you're | |
// actually using change. | |
// | |
// it is based on "Option 3" from this comment: | |
// https://github.com/facebook/react/issues/15156#issuecomment-474590693 | |
import { useMemo } from 'react'; | |
import useStore from './useStore'; | |
import values from 'lodash/values'; | |
export default function usingStoreProps(selector, render) { | |
return function(props) { | |
const [store, dispatch] = useStore(); | |
// the selector must return an object suitable for passing to a component, | |
// analogous to mapStateToProps from react-redux | |
const selection = selector(store); | |
return useMemo( | |
() => render({ ...props, ...selection, dispatch }), | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
[props, ...values(selection)] | |
); | |
}; | |
} |
or we could call other hooks from within selector
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note to self: could it work to use
React.memo
instead ofuseMemo
here, removing the constraint on what can happen insiderender
?