Mikey
Mikey

Reputation: 3017

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.

Upvotes: 47

Views: 34486

Answers (3)

Mikhail Kornienko
Mikhail Kornienko

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

Nelson Javier Avila
Nelson Javier Avila

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

Estus Flask
Estus Flask

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

Related Questions