Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

consistent-return for useEffect

Tags:

reactjs

eslint

When i do something like this

  useEffect(() => {
    if (steps.step2 && !requestKey) {
      const timeoutId = setTimeout(() => startProcess(), 500)
      return () => clearTimeout(timeoutId)
    }
  }, [steps, requestKey, startProcess])

eslint complains me error Expected to return a value at the end of arrow function consistent-return for return () => clearTimeout(timeoutId)

Because when i comment this an error disappears.

// return () => { clearTimeout(timeoutId); }

How to solve this, any ideas?

like image 631
JillAndMe Avatar asked May 08 '26 10:05

JillAndMe


2 Answers

If you're returning in at least one branch, you need to always return a value to follow the rule. It doesn't have to be a function, it just has to be something other than the standalone statement return. This works too:

  useEffect(() => {
    if (steps.step2 && !requestKey) {
      const timeoutId = setTimeout(() => startProcess(), 500)
      return () => clearTimeout(timeoutId)
    }
    return undefined;
  }, [steps, requestKey, startProcess])

Also note that setTimeout(() => startProcess(), 500) simplifies to setTimeout(startProcess, 500).

like image 103
CertainPerformance Avatar answered May 11 '26 10:05

CertainPerformance


When i add this return () => {} at the end of useEffect(() => {...})

Now eslint doesn't complains about this.

  useEffect(() => {
    if (steps.step2 && !requestKey) {
      const timeoutId = setTimeout(() => startProcess(), 500)
      return () => clearTimeout(timeoutId)
    }
    + return () => {}
  }, [steps, requestKey, startProcess])
like image 42
JillAndMe Avatar answered May 11 '26 09:05

JillAndMe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!