From the react official documentation we know that "React relies on the order in which Hooks are called". So is there anything wrong with "reserving" a spot for a hook if I want to call it conditionally?
function Component({flag, depA, depB}) {
if (flag) {
// just "reserving a spot"
useEffect(() => {}, [null, null])
} else {
useEffect(() => {
// ... actual hook
}, [depA, depB])
}
return <></>
}
If this works, would it also work for useCallback
? useLayoutEffect
? useMemo
? useImperativeHandle
?
I've tested all of this and in much more complicated contexts, it seems to work even though the linter complains. Am I missing something?
PS: if it looks kind of useless just like this, it's because the end goal is to have the main part of the hook be lazy loaded with import()
, and before the import is triggered and resolved, just reserve the spots for hooks.