1

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.

1
  • don't put setSize in the dependency array. it's already guaranteed to be constant. Commented Feb 15, 2023 at 1:23

2 Answers 2

4

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 when you don't add size in the dependency array because now you are not using it.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.