/conditionalHookOptions.js Secret
Created
September 27, 2021 18:17
This file contains hidden or 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
// 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