In the docs it says that we should only call hooks at the top level of our components. Due to the API of useEffect, return
is already reserved for the cleanup which made me wonder how I could early exit a useEffect hook to prevent deeply nesting my if statements.
// instead of
React.useEffect(() => {
if (foo){
// do something
}
})
// I would rather write something like
React.useEffect(() => {
if (!foo){
// exit early and stop executing the rest of the useEffect hook
}
// do something
})
How can I achieve this? In my first example, things could quickly get messy with complex conditional logic especially considering that I can't be using useEffect
inside a conditional statement.
return
like in any JS function will work. But first it might be an idea to think about why you need the condition. Sometimes it might be better to split the component up more. For example, lets say we have a component calledMultiEdit
, and what we want to do is have a property callededitType
, this will render two different styles of controls, so it might need differentuseEffect
semantics, rather than useif (!style1) return
etc, you could just create 2 sub components, say calledEditStyle1
&EditStyle2
etc. You can then conditionally render these. – Kowalski!condition
when checking for the condition is clearer. But in any case,if...else if...else
is the right approach and it works fine. Don't forget to clean things up you can break things out into multipleuseEffect
hooks if needed. – Troyes