Skip to content

Instantly share code, notes, and snippets.

@kyleshevlin
Created September 27, 2021 18:17
// You have two options when it comes to making custom hooks do work conditionally
// Conditionally render a renderless subcomponent that will do the work
function AutoSave() {
useAutoSave()
return null
}
function Doc({ shouldAutoSave }) {
return (
<>
{shouldAutoSave && <AutoSave />
<Content />
</>
)
}
// Or make the hook lazy by returning a function to do the work later
function Doc({ shouldAutoSave }) {
const runAutoSave = useAutoSave()
if (shouldAutoSave) {
runAutoSave()
}
return <Content />
}
// Prefer the latter, it's more idiomatic
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment