Skip to content

Instantly share code, notes, and snippets.

@samholmes
Last active August 13, 2020 02:50
Show Gist options
  • Save samholmes/dc2ebcc115762a00502a3c2e364bf4fa to your computer and use it in GitHub Desktop.
Save samholmes/dc2ebcc115762a00502a3c2e364bf4fa to your computer and use it in GitHub Desktop.
/*
To avoid a lot of conditional checks on all consumer components,
what if we had a hook to conditionally render from a context's data?
*/
// I wonder if this will work. Totally untested, but it's a concept.
function ConsumerComponent() {
const data = useContext(SomeContext);
return useConditional(!data, () => {
useEffect(() => {
console.log("I can haz hooks!")
}, [data]);
return <div>Date has been loaded: {data}</div>;
});
}
function useConditional(condition, render) {
return <ConditionalRenderer condition={condition}>{render()}</ConditionalRenderer>;
}
function ConditionalRenderer({condition, children}) {
if (condition) {
return children
}
else {
return null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment