Reputation: 3017
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.
Upvotes: 47
Views: 34486
Reputation: 1412
Please note that in React 18, you might get something like "destroy is not a function" error if you just "return" (return, or return false, or whatever) from useEffect.
That's because React 18 requires you to return a cleanup FUNCTION.
So an easy way out (not the best, I'd assume, but just as a quick fix), could be returning like that:
useEffect(() => {
if (!goodToGo) {
return () => {}
}
console.log("Doing stuff");
}, [goodToGo])
Upvotes: 5
Reputation: 572
I think a simple solution is to create a function and do a return
useEffect(() => {
const fetchData = async () => {
if (!foo) return
}
fetchData()
}, [])
Upvotes: 1
Reputation: 222309
As with any function, it can be exited early with return
keyword.
These two snippets are equivalent:
React.useEffect(() => {
if (foo){
// do something
}
})
React.useEffect(() => {
if (!foo){
return;
}
// do something
})
Upvotes: 56