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])
2
Answers
UseCallback needs to be added to the foo function to make it stable.
const foo = () => {
return ‘foo’
}
const useFoo = () => {
return {
foo
}
}
const foo = () => {
return ‘foo’
}
const fooObj = {
foo
}
const useFoo = () => {
return fooObj
}