Question
How to early exit useEffect hook?
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.