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.
CodePudding user response:
You have added size
in the dependency array. So, the useEffect
will run whenever size
changes. Now, in your useEffect
, you are incrementing size
using the setSize
setter. This will again cause size
to change and again run the useEffect
.
If you want to refer to the previous size
, you can use the callback version of the setSize
.
setSize((previousSize) => previousSize 1)
This way, your linter won't complain.
CodePudding user response:
You aren't supposed to use the size state inside the setSize.
You can change it to
setSize(size => size 1)
And then remove the size from the dependency array.
Can read more here: enter link description here