Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

useEffect infinite loop when updating state and including dependency array

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading