Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 843
Mikey Avatar asked Feb 10 '19 10:02

Mikey


People also ask

Can you return out of a useEffect?

When our code runs and reruns for every render, useEffect also cleans up after itself using the cleanup function. The useEffect Hook is built in a way that we can return a function inside it and this return function is where the cleanup happens.

How do I stop a useEffect?

To get rid of your infinite loop, simply use an empty dependency array like so: const [count, setCount] = useState(0); //only update the value of 'count' when component is first mounted useEffect(() => { setCount((count) => count + 1); }, []); This will tell React to run useEffect on the first render.

How do I run useEffect only once?

Side Effect Runs Only Once After Initial Render You do not want to make this API call again. You can pass an empty array as the second argument to the useEffect hook to tackle this use case. useEffect(() => { // Side Effect }, []); In this case, the side effect runs only once after the initial render of the component.

Does useEffect run after every render?

Does useEffect run after every render? Yes! By default, it runs both after the first render and after every update.


Video Answer


1 Answers

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
})
like image 53
Estus Flask Avatar answered Oct 01 '22 07:10

Estus Flask