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.

 46  32226  46
1 Jan 1970

Solution

 55

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
})
2019-02-10

Solution

 5

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])
2023-04-14