Home > Net >  React useEffect return best practice
React useEffect return best practice

Time:06-15

I am trying to understand if it's against React's best-practices to use return in useEffect, to avoid some logic from being executed. So far in documentation I only see it being used for clean-ups.

I have a candidate which wrote similar logic:

useEffect(() => {
  if (foo === 'bar') {
   baz();
   return;
  }
  xyz();
,[foo]);

Ideally should be one of:

1.

useEffect(() => {
  if (foo === 'bar') {
   baz();
  } else {
    xyz();
  }
,[foo]);
  1. two smaller useEffects
  2. logic separated from useEffect, and is conditional

However, to not have this opinion based. I am trying to find articles on this best-practice? PS. Official React docs do NOT have this kind of approach used ANYWHERE, or mention it other than a clean-up function.

CodePudding user response:

When you return nothing from a function (or useEffect) it defaults to returning undefined; similar thing happens if you just write return. So there is nothing wrong with this:

 if (foo === 'bar') {
   baz();
   return;
  }

So, writing return would be similar to just writing useEffect without return keyword, which is Ok.

Valid things you can return from useEffect are: undefined or a cleanup function.

CodePudding user response:

this question has a lot of information that will help you understand useEffect and cleanup mechanism more : What is the expected return of `useEffect` used for?

edit : this article has what you're looking for : https://www.digitalprimates.net/blog/what-values-should-be-returned-when-using-useeffect-in-react/ as mentioned “An effect function must not return anything besides a function, which is used for clean-up.”

  • Related