I always find this a bit weird with React that it is said to be an anti-pattern to not add all dependencies to the useEffect hook and warnings are shown in the console.
Take this example. I am using swr and useSWRInfinite - see example here and docs here.
My code looks checks that a element is inView and if so it fetches the next page of data.
This all works fine
useEffect(() => {
if (inView) {
setSize(size + 1)
}
}, [inView, setSize])
but if I add size to the dependency array an infinite loop occurs as I am updating the size within useEffect
useEffect(() => {
if (inView) {
setSize(size + 1)
}
}, [inView, setSize, size]) <------ everything breaks
Can anyone advise on the correct way of handling this. After reading through many SO answers and blog posts nothing is any clearer.
setSizein the dependency array. it's already guaranteed to be constant.