reactjsreact-hooksexhaustive-deps

Why does useEffect fire multiple times after adding functions in warnings from the exhaustive-deps linter?


Given a simple hook function useFoo with a simple function foo.

When I use a function inside of useEffect, everything appears to function fine, but I get a waring from exhaustive-deps saying that function must be listed as a dependency.

When I add the function to the deps array it causes the effect to fire repeatedly or even continuously depending on the situation.

Why is foo not stable? Or how do I make the warning go away, and keep my code working properly?

const useFoo = () => {
  const foo = () => {
    return 'foo'
  }
  return {
    foo
  }
}

export default useFoo

Used in a control without dep

  useEffect(() => {
    console.log('i fire 2 times because of React.Strict')
  }, [])

Used in a control with dep

  useEffect(() => {
    console.log('i fire many times')
  }, [foo])

Solution

  • UseCallback needs to be added to the foo function to make it stable.

    const useFoo = () => {
      const foo = useCallback(() => {
        return 'foo'
      }, [])
      return {
        foo
      }
    }